Tigran Muradyan
Tigran Muradyan

Reputation: 512

jquery hover and click conflict

i'm doing active, hover, unhover for logos using jQuery. I know that there is better way, doing it using css, but i need to use jQuery, because the logos are generated in php.

So, here is html.

<li>
   <input type="radio" name="payment_system" id="YANDEXMONEY" value="YANDEXMONEY">
   <label for="YANDEXMONEY"><img class="payment-system-img" src="images/icons/icon-ym.png" /></label>
   <div id="ym-price" class="price"><span>500</span> руб.</div>
</li>

To make it active

$('.payment-system-img').click(function() {
    makeAllInactive();
    makeActive($(this));
});

functions used

function makeAllInactive() {
    $('.payment-system-img').each(function() {
        var imgSrc = $(this).attr('src');

        if(imgSrc.indexOf('-hover') != -1) {
            var src = imgSrc.replace('-hover', '');
            $(this).attr('src', src);
        }
    });
}

function makeActive(img) {
    var imgSrc = img.attr('src').split('.');

    if(imgSrc[0].indexOf('-hover') == -1) {
        img.attr('src', imgSrc[0] + '-hover.' + imgSrc[1]);
    }
}

making it active on hover and inactive on unhover.

$('.payment-system-img').hover(
    function() {
        makeActive($(this));
    },
    function() {
        makeInactive($(this));
    }
);

function used

function makeInactive(img) {
    var imgSrc = img.attr('src');

    if(imgSrc.indexOf('-hover') != -1) {
        var src = imgSrc.replace('-hover', '');
        img.attr('src', src);
    }
}

And here comes the conflict. When i click on image it comes active, but when im unhovering it after click, it comes inactive because hover function. How to do it right way using jQuery, without conflicts? thanks.

Upvotes: 2

Views: 1966

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173582

You could add a class when an item has been selected:

$('.payment-system-img').click(function() {
    makeAllInactive();
    makeActive($(this).addClass('selected'));
});

Then, in the makeInactive() function you check the class first and skip it when the class is present:

function makeInactive(img) {
    if (img.hasClass('selected')) { return; }
    var imgSrc = img.attr('src');

        if(imgSrc.indexOf('-hover') != -1) {
            var src = imgSrc.replace('-hover', '');
            img.attr('src', src);
        }
    }

Lastly, inside the makeAllInactive() you need to remove it:

function makeAllInactive() 
{
    $('.payment-system-img')
        .removeClass('selected')
        .each(function() {
            var imgSrc = $(this).attr('src');

            if(imgSrc.indexOf('-hover') != -1) {
                var src = imgSrc.replace('-hover', '');
                $(this).attr('src', src);
            }
        });
}

Upvotes: 2

Related Questions