0

Can someone help me with this? When the document loads it automatically does the alert. Not when class b1 or b2 is hovered. How do I fix it to make it when b1 or b2 is hovered to then do the alert?

I am sure it has to do with the document.ready function, but I thought it would not alert till the if statement of hover is initiated. So how do I make it work? Thanks!

function hoverHere(){
    if($('.b1').hover()){
        alert('Hello World');
    };
    if($('.b2').hover()){
        alert('Hello World');
    };
}

$(document).ready(function(){
    hoverHere();
})

HTML

<section class="headings">
    <div class="b1">content</div>
    <div class="b2">content</div>
</section>   
3
  • 3
    You are doing it wrong. You need to bind a mouseover or mouseenter event. Also, alert is a horrible choice to use in any mouse events that are not clicks. Commented May 25, 2014 at 9:20
  • I strongly recommend to have this API as bookmark. If you check for the hover() documentation, you would have noticed that you are doing it wrong.
    – KarelG
    Commented May 25, 2014 at 9:23
  • Obviously I am doing it wrong. I will replace the alert with different code. I just am trying to get it working. @ThiefMaster
    – Chipe
    Commented May 25, 2014 at 9:29

2 Answers 2

3

Simply :

$(document).ready(function(){
    $('.b1, .b2').hover(function() {
        alert("Hello world !");
    }); 
})
2

In case you wanted to do something different for each hover:

$(document).ready(function(){
    $('.b1').hover(function() {
        alert("Hello world ! - b1");
    }); 
    $('.b2').hover(function() {
        alert("Hello world ! - b2");
    }); 
}); 

Another way you could do it is:

function hoverHere(){
    $('.b1').hover(function() {
        alert("Hello world ! - b1");
    });
    $('.b2').hover(function() {
        alert("Hello world ! - b2");
    });
}

$(document).ready(hoverHere); 
1
  • Thank you. I do want to do something different with each hover. This will work great!
    – Chipe
    Commented May 25, 2014 at 9:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.