I want a mouseover event to be handled after a delay, and then be inactive until a page refresh.
This is my code thus far:
$(function() {
$("#page-flip").mouseover(function() {
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
});
});
How do I add a time delay to this and than have it inactive after being fully triggered once? Thank you :)
You can use .one() to have an event handler only trigger once:
$(function() {
//bind a mouseover event handler that will fire only once
$("#page-flip").one('mouseover', function() {
//set a timeout so the code runs after half a second
setTimeout(function () {
//run your code here
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}, 500);
});
});
Here is a demo: http://jsfiddle.net/jasper/fWakf/3/
Documentation: http://api.jquery.com/one
You could also use .off():
$(function() {
$("#page-flip").on('mouseover', function() {
//remove this event handler so it doesn't fire in the future
$(this).off('mouseover');
setTimeout(function () {
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}, 500);
});
});
Here is a demo: http://jsfiddle.net/jasper/fWakf/4/
Note that .on() is new in jQuery 1.7 and in this case is the same .bind(). .off() is also new so if you're using older than 1.7 and .bind(), then use .unbind().
Edit This answer is worse than Jasper's. But the pattern it uses doesn't require jQuery, so I'm leaving it up.
Well, you could go simple and use a global variable, or complicated and remove the event entirely.
the simple one looks like this.
var __GlobalEventFired = false;
$(function() {
$("#page-flip").mouseover(function() {
if(!__GlobalEventFired)
{
__GlobalEventFired = true;
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}
});
});
Related
<script>
$(document).ready(function(){
$("#register_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").click(function()
{
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
This is my jquery code for flipping between login and register forms.
Initially the page contains the login form and a link to load the register form. It works the first time to load the register form and a link to load the login form. But it doesn't work after that. It doesn't change from register to login form. How to rectify this?
This is because the listeners are only set on existing elements. When you load something using Ajax (jQuery.load()), there will be no listeners on those new elements. You can fix it by re-initializing the click listeners, after the new content is loaded, like this:
<script>
function listenToClick() {
$("#register_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php", function() {
listenToClick();
});
});
$("#login_link").click(function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php", function() {
listenToClick();
});
});
}
$(document).ready(function(){
listenToClick();
});
</script>
An even better option would be to listen to the click event using the on function. The on function also listens to future elements (the elements created by jQuery.load()).
<script>
$(document).ready(function() {
$("#register_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("register_form.php");
});
$("#login_link").on('click', function() {
$("#login_or_register").empty();
$("#login_or_register").load("login_form.php");
});
});
</script>
You can use .on() to delegate the events like this:
$(document).ready(function(){
$(document).on('click', "#register_link, #login_link", function() {
$("#login_or_register")
.empty()
.load($(this).is('#register_link') ? "register_form.php" : "login_form.php");
});
});
Use event delegation to account for elements that don't exist at run time that may be added to the dom later:
$(document).on('click', '#register_link, #login_link').click(function () {
var url = $(this).is('#login_link') ? "login_form.php" :"register_form.php" ;
$("#login_or_register").empty().load(url);
});
I'm working on a jQuery plugin. To separate my logic I do something like this:
$element.on({
mouseenter: function(){
//do something special
}, mouseleave: function(){
//do something else special
}
});
//more stuffs
and then above this I do that again but with other function body
$element.on({
mouseenter: function(){
//do something not special
}, mouseleave: function(){
//do something else not special
}
});
How does jQuery deal with this ? Will 2nd declaration of mouse events function override the first one ? Sometimes I see both things works but sometimes not.
Will 2nd declaration of mouse events function override the first one ?
No.
How does jQuery deal with this ?
It executes your event handlers in the order in which they were attached. From the documentation (about 40% down the page):
Event handlers bound to an element are called in the same order that they were bound.
So for instance, if you have:
var div = $("#someDiv");
div.on("click", function() { console.log("one"); });
div.on("click", function() { console.log("two"); });
div.on("click", function() { console.log("three"); });
...then clicking the div will give you
one
two
three
...in the console.
Note that it doesn't matter how you found the element to attach the handlers. Let's say you have only one div on the page, it has the id "someDiv", and it's the first child of body (just to make the selectors easy). If you have:
$("#someDiv").on("click", function() { console.log("one"); });
$(document.body).children().first().on("click", function() { console.log("two"); });
$("div").on("click", function() { console.log("three"); });
and you click the div, you'll get
one
two
three
...in the console.
I have few namespaces and I want to reinitialize function inside namespaces on document change in order to be reinitialized every time when the document is modified (*modified = adding/removing new sections on existing dom ).
I have tried this but not working so far:
;namespaceName= {
namespaceFunction1: function() {
$( selector ).on('click', function() {
//my first function run here
})
},
// ************second function in namespace***************/
namespaceFunction2: function() {
$(secondSelector).on('click', function() {
//my second function run here
})
}
}
$(document).on('change', namespaceName.namespaceFunction1() );
$(document).on('change', namespaceName.namespaceFunction2() );
Pls help, ty.
Try this...
$(document).on("DOMSubtreeModified", function () {
namespaceName.namespaceFunction1();
namespaceName.namespaceFunction2();
});
It fires your 2 functions on the DOMSubtreeModified event, which is basically what you were looking for - when the DOM changes.
sounds like you need to listen for the DOMSubtreeModified event like this:
$('body').bind('DOMSubtreeModified', function(){
//your code here
});
I remember having this problem once before but I dont' know which project it was on or how I fixed it.
I have an ajax 'add to favorite' button, and I also have infinite scroll which ajax loads pages when you reach the bottom of the page. The problem is the ajax doesn't apply to the newly appended content:
// Favorites
$('.res-list .star').click(function(){
var starLink = $(this);
var listItem = $(this).parent().parent();
if ($(starLink).hasClass('starred')) {
$(starLink).removeClass('starred');
} else {
$(starLink).addClass('starred');
}
$.ajax({
url: '/favorites/?id=' + $(starLink).attr('data-id'),
type: 'PUT',
success: function() {
if ($(starLink).hasClass('starred')) {
$(listItem).animate({
backgroundColor: '#FFF8E4'
}, 400);
} else {
$(listItem).animate({
backgroundColor: '#ffffff'
}, 400);
}
}
});
return false;
});
You need live event
$('.res-list').on('click', '.star', function() {
// code here
});
or use delegate()
$('.res-list').delegate('.star', 'click', function() {
// code here
});
read about delegate()
read about on()
The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.
The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored. Just like the .live() method, this technique uses event delegation to work correctly.
$('#start') executes the function myFunction() and $('#stop') end it. How do I stop myFunction() from executing?
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').click(function() {
myFunction();
});
$('#stop').click(function() {
//stop myFunction
});
As Daniel pointed out, you actually want to unbind the event handler. You can use unbind for this:
$('#stop').click(function() {
$(document).unbind('mousemove');
});
But this will also remove all other mousemove event handlers, that might be attached by other plugins or similar (I mean, you attach to the document element not a "custom" element, so it can be that other JavaScript code also binds handlers to this element).
To prevent this, you can use event namespaces. You would attach the listener with:
function myFunction() {
$(document).bind('mousemove.namespace', function(e) {
$('#field').html(e.pageY);
});
}
and unbind:
$('#stop').click(function() {
$(document).unbind('mousemove.namespace');
});
This would only remove your specific handler.
You want to use the jQuery bind and unbind methods. For example:
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').bind('click.myFunction', function() {
myFunction();
});
$('#stop').bind('click', function() {
$('#start').unbind('click.myFunction');
});
You're not stopping the function from executing. Your myFunction() simply attaches a callback to an event listener, which is called whenever the mouse is moved on the document. The callback function is invoked and is terminated immediately.
You'd simply want to unbind the callback from the event listener. Check out the other answers for concrete examples.
A better way would be to use bind and unbind, like so:
function myFunction() {
$(document).mousemove(function(e) {
$('#field').html(e.pageY)
});
}
$('#start').bind('click', myFunction);
$('#stop').click(function() {
$('#start').unbind('click', myFunction);
});