If you want to access the document element in your jQuery code, you can simply include [0]
, although this might not be necessary when using jQuery's method of adding event listeners. I recommend using either $('#but').mouseout(etc)
or $('#but').on('mouseout', etc)
.
I have made some adjustments to your jsfiddle so it now works as intended. But here is a brief tutorial for your reference:
There are two main methods for adding event listeners in jQuery as outlined in the documentation; the .on()
method and the .(event)()
method. The latter allows you to add event handlers to jQuery objects instead of using object.(eventName)()
. For instance, to add a click handler to an object:
object.click(function() { console.log('executed'); });
However, this method is not 'live' and won't update if elements are dynamically added. Events are only attached once the document is ready(
$(document).ready(function() { do stuff });
). To attach events to dynamically added elements, use the
.on()
method.
Consider the following HTML scenario:
<div class="wrapper">
<span class="dynamically_added">content</span>
</div>
To attach an event listener to the dynamically added span, include the following in your jQuery:
$(".wrapper").on('click', '.dynamically_added', function() {
console.log('executed');
});
The first parameter of .on()
is the event(s). Multiple events can be attached by separating them with spaces: .on('click hover')
. The second parameter is either the function to execute or the targeted element. In the above example, it is the span. The last parameter is, of course, the function to execute. It is essential to use an anonymous function to refer to the function that needs to be executed, rather than writing it directly there.
I trust this information has been beneficial to you.