execute function on page or not? - javascript

I have recursive function as the following :
scope.$watch('settings.egg', function () {
var index = 0;
function inOrder() {
setTimeout(function () {
$(".egg").eq(index).removeClass("maximize")
$(".egg").eq(index + 1).addClass("maximize")
index++;
inOrder();
}, 3000)
};
$(".egg").eq(index).addClass("maximize")
inOrder();
})
My function execute on load page but I don't want that.
I just want to work click on button not on load page.
How can I do ?
Please..

Why not set up a function that's bound to an ng-click of your button then and set your function within that? For example:
scope.buttonClick = function() {
scope.watchFunc = scope.$watch('settings.egg', function () {
var index = 0;
function inOrder() {
setTimeout(function () {
$(".egg").eq(index).removeClass("maximize")
$(".egg").eq(index + 1).addClass("maximize")
index++;
inOrder();
}, 3000)
};
$(".egg").eq(index).addClass("maximize")
inOrder();
})
}
You'd store this in a scope variable so that you could easily call it from another function later on to cancel the $watch. And in your markup:
<button ng-click="buttonClick()">Click me to set the watch</button>

Related

clearInterval() not working and returns no errors

I would like to run a function, when a checkbox is checked and stop that function, when the checkbox is not checked.
This is how I tried it:
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
}
else {
clearInterval(autoInterval);
}
});
The problem is clearInterval() does not work and I get no errors.
https://jsfiddle.net/n339tzff/9/
It will work if my code looks like this:
// Interval
var autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
// Auto Play
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval;
}
else {
clearInterval(autoInterval);
}
});
But then I have another problem... I only want to run the function navi('next') when I click on the checkbox and not at the beginning.
When you click, it calls the setInterval and stores the result of the call in the autoInterval and after ending the function removes it. So you store and lost the value of your variable every time in the same call.
Declare the autoInterval variable outside of the event handler, to make it independent from the event handler's scope. Also you can wrap your function with a IIFE to not mutate this variable outside
(function() {
var autoInterval;
$('#auto').on('click', function() {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function() {
navi('next');
}, 1500);
} else {
clearInterval(autoInterval);
}
});
})();
You should define autoInterval outside of the event handler function, as after the event has run this variable would be 'discarded'/un-accessable.
var autoInterval = null;
$('#auto').on('click', function () {
if ($(this).is(':checked')) {
autoInterval = window.setInterval(function () {
navi('next');
}, 1500);
}
else if(autoInterval !== null) {
clearInterval(autoInterval);
autoInterval = null;
}
});

Dynamically added function still running even after remove from DOM

This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
I load this function to a div using;
$("#temporarycontent").load("dynamicjs.php");
And when I do
$("#temporarycontent").empty();
The script is still running. How can I stop it run ?
You can't, you need a handle to the intervalId returned by the setInterval function or provide an API on the plugin in order to destroy it and cleanup after itself. The easiest way would be to attach the state of the plugin to the DOM element on which it was applied.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>
You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)
let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
(function ($) {
$.fn.baslatmesajlari = function() {
interval = setInterval(function () {
console.log('I am running')
}, 5000)
return this
}
})(jQuery)
})
$("body").baslatmesajlari()
And then:
$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.
Hope it helps.

DIV should be refreshed only once

success: function (result) {
if (result == 1) {
var auto_refresh = setInterval(function () {
$('#myDiv').fadeOut('slow', function () {
$(this).load('/echo/json/', function () {
$(this).fadeIn('slow');
});
});
}, 1025544);
}
}
Friends on success function I have to refresh the myDiv DIV only once but as the above code the DIV is keep on fade out and fade in continuously instead it should work only once
setInterval() repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It will continue to do so until clearInterval is called.
It is easiest just to use setTimeout(), which just delays the function being called for the specified time:
var auto_refresh = setTimeout(function() {
$('#myDiv').fadeOut('slow', function() {
$(this).load('/echo/json/', function() {
$(this).fadeIn('slow');
});
});
}, 1025544);
using a variable name auto_refresh kind of indicates you want it to repeat. also -> 1025544ms = 17mins. so it will refresh every 17 mins.
if you want it to not show, wait 17mins then show, use #Jacod Grays Answer.
if you just want it to show, remove the setInterval like so :-
success: function (result) {
if (result == 1) {
$('#myDiv').fadeOut('slow', function () {
$(this).load('/echo/json/', function () {
$(this).fadeIn('slow');
});
});
}
}

Javascript function scope - to use console.log or not?

Two functions:
First: Closes a stickyFooter that is fixed to the bottom of the page onclick of the cross.
jQuery:
jQuery(document).ready(function() {
function closeSticky() {
jQuery('.stickyFooter').hide();
jQuery.cookie('stickyNewsClosed', 'yup', {
path: '/',
expires: 30
});
}
});
Second: This function fades in/fades out two divs, and stops when there's focus to an input area. What needs to happen now is when the stickyfooter is closed it needs to call the clearTimeout in this separate function:
jQuery(document).ready(function () {
// check if both divs are visible
if ((jQuery('.footerPromoBannerWrapper').is(':visible')) && (jQuery('.stickyFooter').is(':visible'))) {
// Local variable for cancel of fades
var stickyTimeout;
// Set sticky as display:none
jQuery('.stickyFooter').hide();
// Switch in
window.switchIn = function () {
jQuery('.footerPromoBannerWrapper').fadeToggle(function () {
jQuery('.stickyFooter').fadeToggle(function () {
stickyTimeout = setTimeout(function () {
window.switchOut();
}, 3000);
});
});
};
// Switch out
window.switchOut = function () {
jQuery('.stickyFooter').fadeToggle(function () {
jQuery('.footerPromoBannerWrapper').fadeToggle(function () {
stickyTimeout = setTimeout(function () {
window.switchIn();
}, 3000);
});
});
};
stickyTimeout = setTimeout(function () {
window.switchIn();
}, 5000);
jQuery('input#emailsignup').focus(function() {
clearTimeout(stickyTimeout);
});
} // End of both divs are visible if statement
});
Question:
How do I combine both in order to call the timeOut feature as part of the close of the sticky footer? Something like this?
First function amendment:
function closeSticky() {
jQuery('.stickyFooter').hide();
jQuery.cookie('stickyNewsClosed', 'yup', {
path: '/',
expires: 30
});
stopAnimation();
}
Second function amendment:
function stopAnimation() {
jQuery('input#emailsignup').focus(function() {
clearTimeout(stickyTimeout);
});
} // End stopAnimation function
console.log(function stopAnimation());
You have jQuery inside the functions, so i would suggest moving the 2 functions inside the dom ready scope. Your cleartimeout is probably calling in udefined.

How to make this script pause on hover?

I'm new to jQuery and I need a bit of help. I'm using this jQuery script as a testimonial rotator and it works like a charm but I just need to make one small tweak. I need it to be able to pause on hover and then restart when the mouse leaves the div. How can I do this?
This is the script I'm using:
function fadeMyContent() {
$(".testimonial:first").fadeIn(1000).delay(3000).fadeOut(1000,
function() {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}
fadeMyContent();
});
Here is a JSFiddle.
There is a plugin that will provide all the functionality you need and be more reliable called jQuery Cycle 2.
It provides a 'pause-on-hover' option when initialising it.
change the definition of fadeMyContent (also called as destroying function) on hovering on ul#testimonial-rotator and on hover-out change it to old definition again. I have used setTimeout in place of delay because delay is not cancellable.
$(document).ready(function () {
var fadeMyContent;
var t
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
var fadeMyContentDummy = function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent()
});
}
fadeMyContent();
$('#testimonial-rotator').hover(function (e)
{
window.clearTimeout(t)
$('.rotate:first').clearQueue()
fadeMyContent = function () {
return false;
}
},
function (e)
{
fadeMyContent = function () {
$(".rotate:first").fadeIn(1000)
t = setTimeout(function () {
$(".rotate:first").fadeOut(1000,
function () {
$(this).appendTo($(this).parent());
fadeMyContent();
});
}, 3000)
}
fadeMyContentDummy()
})
});
DEMO

Categories

Resources