Only run function after custom function complete jQuery - javascript

I normally do e.g.:
$(".item").fadeIn(function(){
alert('done');
});
Which works? (I believe is correct?) but how do I do this with custom functions?
E.g.
$(".item").customFunction(function(){
customFunctionTwo();
});

Basically it will look like this
$.fn.customFunction = function (callback){
//some code
callback();
}
$('.item').customFunction(function () {
customFunctionTwo();
});

I guess you should be looking at promises https://api.jquery.com/promise/
$.fn.customFunction = function (callback){
var myFn = function(){
/* your code along with settimeout as well if you choose*/
//example
return $( "div" ).fadeIn( 800 ).delay( 1200 ).fadeOut();
}
$.when( myFn() ).done(function() {
callback();
});
}
$('.item').customFunction(function () {
customFunctionTwo();
});

Related

how can i add function to jquery event

On mouseover event i want to call function which will do somethig when the mouse will be over on images but i dont know how to write code for it.
function reload(){
$("img.lazy").lazyload({
effect : "fadeIn",
event:"mouseover"
});
}
eg:-
function reload(){
$("img.lazy").lazyload({
effect : "fadeIn",
event:function(moueover)
{
//do somthing here
}
});
}
You want to use mouseenter:
$('.test').on('mouseenter', function() {
alert( 'mouse is over here' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Hover here</div>
Let's see if this works for you
$(function() {
$("img.lazy")
.mouseover(function() {
console.log("Mouseover");
});
});
You can d like this
jQuery('#youdomid').hover(function(){
// do your stuff here
//, your mouse has entered
alert(2);
},
function (){
// your mose leave the element
// do the stuff what you want
alert("leaved");
}
)
You can also use .hover function
$( "img.lazy" ).hover(function() {
$( this ).fadeOut( 100 );
$( this ).fadeIn( 500 );
});
$(document).ready(function(){
$("img.lazy").lazyload({effect : "fadeIn"}, function() {
mousehover();
});
}
function mousehover(){
//do something mousehover stuff on here
}
You can just use the event mouseenter below:
$('.lazy').on('mouseenter', function() {
console.log('foo');
});

JavaScript setInterval inside bind

I am trying to make an infinite periodic get loop:
<script type=text/javascript>
$(function() {
$('a#log').bind('click', setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000));
});
</script>
If I do this
<script type=text/javascript>
$(function() {
$('a#log').bind('click', function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
});
});
</script>
All works well, but without infinite loop.
As #sacho say, setInterval() returns a Number. You are binding that number as your click handler instead a function. That's why is not working, but...
You can do something like this is just want to call the ajax function every time is finished, you can't be sure that your response will be every 2000ms.
$('a#log').click(function (e) {
e.preventDefault();
infiniteLoop();
})
function infiniteLoop() {
$.get(
$LOG + '/json_test',
{},
function(data) {
$("#logs").html(data.replace('\n', '<br/>'));
infiniteLoop();
}
);
}
Note: Use jQuery (specially to manage the DOM) every time you can if you already loaded the library
You need wrap your setInterval function in a intermediate function to prevent it from executed before your click. In other word, a function inside a function.
$(function () {
$('a#log').bind('click', function () {
setInterval(function () {
$.get('example.json',{}, function (data) {
$('#logs').html(JSON.stringify(data).replace('\n', '</br>'));
});
}, 2000);
});
});
JSfiddle Working Demo: http://jsfiddle.net/x13sruaf/
$('a#log').on('click', infiniteLoop);
function infiniteLoop() {
setInterval(function() {
}, 2000);
}
You can try this :
<script type=text/javascript>
$(function() {
var refreshIntervalId;
$('a#log').bind('click', function (){
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000);
});
});
</script>

jQuery Combine delegate statements

I have the following jQuery code at 2 places of the same JS file;
$("#myGrid").delegate(".icon-right", "click", function() {
//Some code
});
$("#myGrid").delegate(".icon-down", "click", function() {
//Some code
});
So the diff is I am listening to click events on icon-down/icon-right
Is it possible to optimize / merge these 2 statements ?
Combine both of them
$("#myGrid").delegate(".icon-right", "click", function () {
//Some code
}).delegate(".icon-down", "click", function () {
//Some code
});
Use .on() after jQuery 1.7
Make the selector match both:
$("#myGrid").delegate(".icon-right,.icon-down", "click", function() {
//Some code
});
Try to use the multiple selector,
same function for all the elements:
$("#myGrid").delegate('click','.icon-right,.icon-down', function(e){
});
different functionality for different elements:
$("body").delegate('click','.icon-right,.icon-down', function(e){
if ($(this).is('.icon-right')) { }
else { }
});
yes you can do this:
$("#myGrid").delegate(".icon-right, .icon-down", "click", function () {
if(this.className === 'icon-right'){ // some code}
else if(this.className === 'icon-down'){ // some code}
});
If you are using jquery 1.7+ then you can try with .on() with switch:
$("#myGrid").on("click", ".icon-right, .icon-down", function () {
switch(this.className){
case 'icon-right':
//some code
break;
case 'icon-down':
// some code
break;
}
});

Is it possible to bind multiple functions to multiple delegation targets in one place?

As it is possible to define multiple event handlers in one single function in jQuery like this:
$(document).on({
'event1': function() {
//do stuff on event1
},
'event2': function() {
//do stuff on event2
},
'event3': function() {
//do stuff on event3
},
//...
});
Then again we can do this:
$(document).on('click', '.clickedElement', function() {
//do stuff when $('.clickedElement') is clicked
});
I was wondering if it is also possible to do something like this (the following code does not work, it's just for illustration):
$(document).on('click', {
'.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
},
'.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
},
//... and so on
});
This code gives me an error complaining about the "," after '.clickedElementX'. I also tried it like this:
$(document).on('click', {
'.clickedElement1': function() {
//do stuff when $('.clickedElement1') is clicked
},
//... and so on
});
Then I don't have the error but also the function is not executed. Is there a way to collect all the click handlers in one place like this or would I have to always do it like this:
$(document).on('click', '.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
});
$(document).on('click', '.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
});
//... and so on
You can chain :
$(document).on({
click: function() {
//click on #test1
},
blur: function() {
//blur for #test1
}
}, '#test1').on({
click: function() {
//click for #test2
}
}, '#test2');
FIDDLE
Short answer: no, you have to bind them all separately.
Long answer: You can create an "infrastructure" for your site and have all events in one place. e.g.
var App = function(){
// business logic
return {
Settings: { ... },
Events: {
'event1': function(){
},
'event2': function(){
},
'event3': function(){
}
}
}
}();
Then wiring it up involves:
$(document).on(App.Events);
Then internally you can add then new bindings to your App object but still remains wired up in only one place (as far as jQuery is concerned). You could then make some kind of subscriber model within App (e.g. App.Subscribe('click', function(){ ... })) and each new subscription still is only wired through the single .on() binding.
but, IMHO, this is a lot of overhead with very little pay-off.
$(document).on('click' , function(e){
if($(e.target).hasClass("some-class")){
//do stuff when .some-class is clicked
}
if($(e.target).hasClass("some-other-class")){
//do stuff when .some-other-class is clicked
}
});
you can choose any some-class you want
It can be easily done, really:
$(document).ready(function()
{
$(this).on('click', '.one, .two',function()
{
if ($(this).hasClass('one'))
{//code for handler on .one selector
console.log('one');
}
else
{//code for handler on .two selector
console.log('two');
}
console.log(this);//code for both
});
});
If multiple events is what you're after:
$(document).ready(function()
{
$(this).on('click focus', '.one, .two',function()
{
if (event.which === 'click')
{
if ($(this).hasClass('one'))
{
console.log('one');
}
else
{
console.log('two');
}
}
else
{
console.log('focus event fired');
}
console.log(this);
});
});
Play around with this: here's a fiddle
documentation on event
jQuery's on, which is used here as though it were delegate
you can use a helper function:
function oneplace(all){
for (var query in all){
$(query).on('click', all[query]);
}
}
and then call:
oneplace(
{'#ele1':function(){
alert('first function');
},
'#ele2':function(){
alert('second function');
}});
jsfiddle here: http://jsfiddle.net/5zwkf/

How to call function in jquery plugin?

(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
};
//.....
};
})(jQuery);
call it in doucument ready in another file
$('#top_slides').top_islides();
$('#top_slides').top_islides().ajax_init();
I thought it should work ,I got an error, what's the problem?
Do it like this:
(function($) {
//Assuming $.fn.top_islides is defined
$.fn.top_islides.ajax_init = function(){
init_islides();
setTimeout(picmove,300);
};
//.....
})(jQuery);
Or
(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(picmove,300);
};
return {
ajax_init: ajax_init
};
});
//.....
})(jQuery);
Try something like this as in the example below:-
<script type="text/javascript">
$.someplugin = {
CallMe : function() {
alert("You called?");
},
otherstuff : function() { alert("other stuff!"); }
};
$.someplugin.CallMe();
$.someplugin.otherstuff();
</script>
when using var inside a function, it will make the element "private". it's a hacky way to make visibility in Javascript work, while true class structure don't come to Javascript.
You need to either set it to the prototype of your function or to return an object
(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
};
return {
'ajax_init': ajax_init
};
//.....
};
})(jQuery);
or
(function($) {
$.fn.top_islides = function(){
//.....
};
$.fn.top_islides.prototype.ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
}
})(jQuery);
but in your case, you won't be using prototype, since you aren't instantiating a new top_islides object, but accessing through jQuery, so the first option is your best bet.
Imo, best solution is used trigger which is cleaner because you can keep the chainable plugin system.
You can declare event handler in your plugin declaration and trigger from outside:
(function($) {
$.fn.top_islides = function(){
this.on ('init_islides', function(){
setTimeout(function(){picmove()},300);
};
//.....
};
})(jQuery);
$( "button" ).click(function () {
$( "p" ).trigger( "init_islides");
});
DOC can be found here : http://api.jquery.com/on/

Categories

Resources