0

I'm using the code below, the .click action works fine on its own, as soon as I add .hover, then .hover works and .click stops working. Any idea why this happens and how to fix it?

$('#11').click(function(){
    $('#widget').load('../212/?id=11');
    $(this).attr("src", "<?php bloginfo('stylesheet_directory'); ?>/images/category-fantasy-32-disable.png");
});
$('#11').hover(
function () {
    //hover event
    $(this).attr("src", "<?php bloginfo('stylesheet_directory'); ?>/images/category-fantasy-32-disable.png");
},
function () {
   //hover out event 
   $(this).attr("src", "<?php bloginfo('stylesheet_directory'); ?>/images/category-fantasy-32.png");
});
2
  • 1
    it could be because when you click and move the mouse out the mouseout event will get triggered resulting in the src being changed Commented Oct 19, 2013 at 5:10
  • @ArunPJohny oh my God, you're a genius! Commented Oct 19, 2013 at 5:23

1 Answer 1

1

The solution is to bind to click and hover both. Here is a sample code

$('p').on('click hover', function () {
    alert("Clicked");
});

$('p').hover(
    function(){
      console.log("X");
    },
    function(){
        console.log("Y");
    }
);

This will trigger both hover in and hover out method. and if you click it works as well. Working link: http://jsfiddle.net/43BW4/

Sign up to request clarification or add additional context in comments.

4 Comments

Funny, I don't want to hijack this post, but I was just about to post almost the exact same question. You fiddle works just as you say, but when applying it with addClass instead of just logging to the console, I still can't get it to work. I've forked your fiddle and modified it. What I'm trying to do is make the paragraph turn green when hovered, return to black when hovered off, but stay green if clicked. What am I doing wrong? jsfiddle.net/dfjosh/LxwHz
This is because as soon as you hover out which is basically mouseleave event the class is removed irrespective you clicked or not. Try adding a flag when element is clicked.
@wetjosh This answer worked for me
Great! That is what I was saying. Add a flag once you have clicked the element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.