user3787706
user3787706

Reputation: 659

jquery hover not firing

i'm adding new clients with socket messages AFTER domready. i want to expand them on hover.

read some answers here, but nothing works. i don't know why

i tried

socket.on('newStudentJoined', function studentJoined(msg) {
    console.log(msg.student + ' joined the room');
    $(document.createElement('div'))
        .attr('class', 'studentIcon closed col-md-2 ' + msg.student)
        .text(msg.student + ' 4r3 g345t g354 g54 ght65 g45t 3f4 f4 f4 534 g534')
        .on('hover', function() {
            console.log('hovering');
            $(this).toggleClass('closed').toggleClass('open');
        })
        .appendTo('#joinedClients');
});

and

$('.studentIcon').on('hover', function() {
    console.log('hovering');
    $(this).toggleClass('closed').toggleClass('open');
});

but not even the "hovering" console log comes out. the selector is correct, if i log it, it highlights the exact element. to make sure:

<div id="joinedClients" class="row">
    <div class="studentIcon closed col-md-2 test">test 4r3 g345t g354 g54 ght65 g45t 3f4 f4 f4 534 g534</div>
</div>

what's wrong here?

Upvotes: 5

Views: 6048

Answers (4)

Amar Singh
Amar Singh

Reputation: 5622

use mouseover instead

$(document).on('mouseover', '.studentIcon',function() {
    console.log('hovering');
    $(this).toggleClass('closed').toggleClass('open');
});

OR USE

$(document).on("mouseenter mouseleave", ".studentIcon", function (e) {
  if (e.type == "mouseenter") {
    // check if it is mouseenter, do something
  } else {
    // if not, mouseleave, do something
  }
});

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

Upvotes: 5

calumbrodie
calumbrodie

Reputation: 4792

It is because you are binding the event before the element in question exists (because you are creating the element with javascript).

You need to either bind the event after creating it, or target your listener as follows

$('#joinedClients').on('hover', '.studentIcon', function() {
    console.log('hovering');
});

Upvotes: 2

Nick White
Nick White

Reputation: 2061

'hover' is not an actual event. jQuery provides a helper function .hover(enterfunc, leavefunc) that is equivalent to:

$('#mydiv').on({'mouseenter': enterfunc, 'mouseleave': leavefunc})

Upvotes: 1

Cruiser
Cruiser

Reputation: 1616

Since you're using JQuery, use .hover() :

$('.studentIcon').hover(//stuff);

Upvotes: 1

Related Questions