HTMellis HTMellis - 6 months ago 9
jQuery Question

Moving between 4 buttons and have roll overs stay clicked between

I have seen a few things close to what I want but am not sure how to implement to what I'm doing.

The below code all works fine but have now been asked to make the hover stay in place when each button is clicked. How would I go about this? Or is it better to start again using buttons and not divs?

Here is a jsfiddle (not sure why all the divs are showing here, live only the first one does which is correct)

Example of button:

<div id="tab1" class="tab" style="height:50px; width:160px; background-color:#CCC; float:left;">
<img src=".../images/landing/terms-coach.jpg" onmouseover="this.src='.../images/landing/terms-coach-col-2.jpg'" onmouseout="this.src='.../images/landing/terms-coach.jpg'" />
</div>


https://jsfiddle.net/uqxdum1o/

Bat Bat
Answer

I've modified the markup and JS a bit to get there but I think this code should fulfil the tab requirement and remove some of the inline JS.

Essentially, store the active image src in an attribute for each tab button:

<div id="tab1" class="tab" style="..." 
    data-image-active="./images/button1-active.jpg"
    data-image="./images/button1.jpg">
    <img src="./images/button1.jpg" />
</div>

Then use this to set active state in your javascript for each tab button. I've moved your current code for click handling into this each loop too.

$(document).ready(function(){
    var $contents = $('.tab-content');
    $contents.slice(1).hide();
    $('.tab').each(function() {
        $(this).hover(function() {
                setButtonActive($(this));
            }, function() {
            if (!$(this).hasClass('active')) {
                setButtonInactive($(this));
            }
        });
        $(this).click(function() {
            resetAllButtons();
            setButtonActive($(this));
            $(this).addClass('active');

            var $target = $('#' + this.id + 'show').show();
            $contents.not($target).hide();
        })
    });
});

function setButtonActive(button) {
    var img = button.find('img'),
        imgSrc = button.attr('data-image-active');
    img.attr('src', imgSrc);
}
function setButtonInactive(button) {
    var img = button.find('img'),
        imgSrc = button.attr('data-image');
    img.attr('src', imgSrc);
}
function resetAllButtons() {
    $('.tab').removeClass('active').each(function() {
        setButtonInactive($(this));
    });
}
Comments