Adding delay to jquery event on mouseover - javascript

I am trying to add a simple delay to a mouseover event of a child and having difficulties. (Still learning!)
This enables me to show the popup after a delay, but shows all of them simultaneously:
onmouseover='setTimeout(function() { $(\".skinnyPopup\").show(); }, 600)'
and this works to show only the popup I want with no delay:
onmouseover='$(this).children(\".skinnyPopup\").show()'
but the combination does not:
onmouseover='setTimeout(function() { $(this).children(\".skinnyPopup\").show(); }, 600)'
Any help would be appreciated. Thanks!

You need to define what this is when it executes, something like this would work:
setTimeout($.proxy(function() { $(this).children(".skinnyPopup").show(); }, this), 600)
Or just use .delay(), like this:
$(this).children(".skinnyPopup").delay(600).show(0);
Both of the above are quick fixes, I suggest you move away from inline handlers and check out an unobtrusive method (see this answer by Russ Cam for some great reasons), for example:
$(function() {
$('selector').mouseover(function() {
$(this).children(".skinnyPopup").delay(600).show(0);
});
});

It's because this is bound to the global context, not the element. Use something like the following instead:
// put this in your document head -- replace element with a selector for the elements you want
$(function () {
$(element).bind("mouseover", function () {
var e = $(this);
setTimeout(function () { e.children(".skinnyPopup").show(); }, 600);
});
});
If you're adamant about inline event handlers, the following should also work:
onmouseover='var self = this; setTimeout(function() { $(self).children(\".skinnyPopup\").show(); }, 600)'

Related

Call user defined jQuery function with JS

I use a jQuery window libray https://github.com/humaan/Modaal
which triggers events this way $("class of element").modaal({arg1, arg2,...});
--- I updated my question here to make it more general and used an iframe / Html instead of an external svg ---
To trigger an element e.g. in an external Html which is loaded within an iframe, I applied the following code to the iframe:
<iframe src="External.html" id="mainContent" onload="access()"></iframe>
which calls this function:
function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}
Actually it will only work on every second click. Any idea what I did not consider properly?
Best
You do not need to wait windows loading but iframe only:
$(function() {
$("#mainContent").bind("load",function(){
var myIframeElement = $(this).contents().find(".modaal");
myIframeElement.modaal({
content_source: '#iframe-content',
type: 'inline',
});
});
});
The reason why it did not work was that the iframe was not completely loaded, while jQuery tried to attach the function. As $(document).ready(function(){} did not work, the workaround was to initialize it with
$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});
This worked properly to attach the functionallity to an element within the iframe.
Actually modaal will vanish the envent handler after the overlay was opened and closed again.
So maybe someone wants to trigger an iframe element for modaal, too, here is a setup which would solve this issue.
(It can be optimised by #SvenLiivaks answer):
$(window).on("load", function() {
reload();
});
function reload() {
var length = $("#iframeID").contents().find("#IDofDIVelement").length;
// The following check will return 1, as the iframe exists.
if (length == 0) {
setTimeout(function() { reload() }, 500);
} else {
$("#iframeID").contents().find("#IDofDIVelement").modaal({
content_source: '#modalwrapper',
overlay_close: true,
after_close: function reattach() {
reload();
}
});
}
}

How to find JS function name?

I have implemented on a website a picture gallery that does not allow (it seems) the auto sliding. So at the moment I have to push on a button to see the next picture. My purpose is to catch the function that allows to move to the next picture and to set a timeout to go to the next picture automatically.
How can I get the JS function name using Google Chrome developer tools?
Thank you
UPDATE
This is the Gallery script: http://tympanus.net/Development/ScatteredPolaroidsGallery/
I would like to implement auto sliding on it
source for code proposal from: https://github.com/codrops/ScatteredPolaroidsGallery/issues/4
(function() {
function autoSliding(timeout) {
var self = this;
clearTimeout(self.timeOut);
self.timeOut = setTimeout(function() {
self._navigate('next');
}, timeout);
}
new Photostack( document.getElementById( 'photostack-1' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
new Photostack( document.getElementById( 'photostack-2' ), {
afterShowPhoto: function(context) {
autoSliding.call(context, 3000)
},
afterNavigate: function(context) {
autoSliding.call(context, 3000)
}
});
}())
This should do the work
$('.navigate-next').click();
Or for auto scroll
setInterval(function(){$('.navigate-next').click();},1000);
Change 1000 for whatever you wish
If you are allowed to use jquery in your code, then, you can use $._data() method.
syntax is $._data($("selector of the element")[0], "events")
This will return an Object of all events bounded to that element. Then get the click event and call the handler attribute of the click event.

Remove Scroll Binding Without Removing Others with Jquery

Is there a way to remove the binding below, without removing other bindings on that element that deal with scroll? I tried the unbind('scroll', scrollHandler) and it didnt work also. I have another scroll binding that is removed because of this. Is there a way to do this with a namespace?
var scrollHandler = function () {
// Inner Logic
};
windowElement.unbind('scroll').scroll(scrollHandler);
Fixed it by using this.
windowElement.unbind('scroll.fixedTop').bind('scroll.fixedTop', scrollHandler);
You can use on() and off():
http://jsfiddle.net/STPcy/
var handler1 = function() {
console.log('handler1');
};
var handler2 = function() {
console.log('handler2');
};
$('#myDiv').on('click', handler1);
$('#myDiv').on('click', handler2);
$('#myDiv').off('click', handler1);
This results in only handler2() being called.

Need Help for better practice Jquery codes

I am trying to make my jquery codes look better here. My functions are working correctly but I was wondering if anyone can make my codes less ugly. Thanks a lot!
HTML
<div class='image_layout'>
<a href='#'><img src=' a.jpg '/></a>
<br><p class='credits'>hahahah
<br>Agency: Agency1
<br>Picture ID: 5 </p>
</div>
jQuery
$('#image_layout').on('hover', 'img', function() {
$(this).parent().next().next().fadeIn('fast');
})
$('#image_layout').on('mouseout', 'img', function() {
$(this).parent().next().next().fadeOut('fast');
})​
You can pass two functions to jQuery hover - one for mousein, one for mouseout. You can make this change as long as you don't have dynamically added images. Your code would also be a lot simpler if the element you are fading has an ID or class:
$('#image_layout img').hover(
function () {
$(this).closest('.someClass').fadeIn('fast');
},
function () {
$(this).closest('.someClass').fadeOut('fast');
}
);
$('.image_layout').on('hover', 'img', function (e) {
if(e.type == 'mouseover') {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
} else {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
}
})
You could also have done:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeIn('fast');
}, function() {
$(this).closest('.image_layout').find('.credits').stop().fadeOut('fast');
});
If you're sure that nothing other than hovering the image will cause the element to fade, you could simply write:
$('.image_layout').on('hover', 'img', function() {
$(this).closest('.image_layout').find('.credits').stop().fadeToggle('fast');
});
Look into Douglas Crockford's JS Style Guide. He'd make your code look something like (with improvements):
var obj = $('#image_layout img');
obj.mouseover( function(){
$(this).parent([selector]).next([selector]).fadeIn('fast');
});
obj.mouseout( function(){
$(this).parent([selector]).next([selector]).fadeOut('fast');
});
You don't need the on, just call the function directly.
I would use .eq as opposed to two next statements, additionally, hover takes two functions, the first being for the mouseenter event, and the second for mouseout
$('#image_layout').hover('hover', 'img', function () {
$(this).parent().eq(2).fadeIn('fast');
}, function () {
$(this).parent().eq(2).fadeOut('fast');
})
References
Take a look at eq here
Read over hover here

why is my element not targeted when reload through AJAX

I'm using object literals on my project. I'm targeting selecting with jquery. It works fine the first time but when the part I'm targeting is reloaded with AJAX I can't target those element anymore. But I look into firebug they're there...
I'm even doing console.log() to test if my code works and it works but it just doesn't want to pick those. So in order for it to work, I have to refresh the entire browser.
Do you know what's the deal with AJAX dom reload and selectors.
I think it's something to do with the DOM reloading and redrawing itself or something along those lines...
Here is my code:
Module.editWishlistTitle = {
wishListContent: $('.mod-wish-list-content'),
title: $('.title').find('h2'),
titleTextField: $('#wishlist-title-field'),
titleInnerContainer: $('.title-inner'),
editTitleForm: $('.edit-title-form'),
submitCancelContainer: $('.submit-cancel'),
notIE9: $.browser.msie && $.browser.version < 9,
edit: function () {
var fieldTxt = this.titleTextField.val(),
editForm = this.editTitleForm,
titleParent = this.titleInnerContainer,
fieldCurrentTitle = this.title.text();
this.titleTextField.val(fieldCurrentTitle);
this.submitCancelContainer.removeClass('hidden');
if (!this.notIE9) {
editForm.css('opacity', 0).animate({ opacity: 1 }).removeClass('hidden');
titleParent.addClass('hidden').animate({ opacity: 0 });
console.log(editForm);
} else {
editForm.removeClass('hidden');
titleParent.addClass('hidden');
}
}
init: function () {
var self = this;
console.log(this.editTitleForm);
//edit
this.wishListContent.delegate('.edit-title a', 'click', function (e) {
self.edit();
e.preventDefault();
});
};
If you are replacing an element on the page, you are destroying the original reference to the element. You need to redo the reference to point to the new element.
Create a new method in your code that (re)initializes the references you need. Instead of adding them in the odject, set them in the method.
Basic idea:
Module.editWishlistTitle = {
wishListContent: $('.mod-wish-list-content'),
title: $('.title').find('h2'),
//titleTextField: $('#wishlist-title-field'),
...
...
initReferences : function(){
this.titleTextField = $('#wishlist-title-field');
},
...
...
init: function () {
this.initReferences();
...
...
And when your Ajax call comes back you just need to call initReferences again.
After DOM ready, if you inject any data / class / id will not be available in DOM, so better you use live or delegate to get your new data access.
http://api.jquery.com/delegate/
Best to use delegate, that will take care your new data loaded after dom ready, that way you can avoid to refresh /reload your page.

Categories