How to stop JavaScript from running automatically? - javascript

This is a script I use in my website.
How can I stop the script from running automatically and instead be run upon mouse click ?
var nbOptions = 8;
var angleStart = -360;
// jquery rotate animation
function rotate(li,d) {
$({d:angleStart}).animate({d:d}, {
step: function(now) {
$(li)
.css({ transform: 'rotate('+now+'deg)' })
.find('label')
.css({ transform: 'rotate('+(-now)+'deg)' });
}, duration: 0
});
}
// show / hide the options
function toggleOptions(s) {
$(s).toggleClass('open');
var li = $(s).find('li');
var deg = $(s).hasClass('half') ? 180/(li.length-1) : 360/li.length;
for(var i=0; i<li.length; i++) {
var d = $(s).hasClass('half') ? (i*deg)-90 : i*deg;
$(s).hasClass('open') ? rotate(li[i],d) : rotate(li[i],angleStart);
}
}
$('.selector button').click(function(e) {
toggleOptions($(this).parent());
});
setTimeout(function() { toggleOptions('.selector'); }, 100);//# sourceURL=pen.js
example link link = http://www.jqueryscript.net/demo/Animated-Circle-Menu-with-jQuery-CSS3/index.html

If I am not mistaken, you don't want your script to start the Animation automatically on pageload.
So you simply have to remove the lase line from the code:
setTimeout(function() { toggleOptions('.selector'); }, 100);
This way, the animation is only started when you manually click on .selector button.

Related

Mouse Wheel within jquery .animate

I have created some JavaScript to scroll up and down my DIV which has a overflow. I already have an up and down button that works fine with this code, I want to know how I can also add the mouse-wheel to scroll, below is my code:
var t = 0;
function MoveUp() {
t += 665;
if (t > 0) t = 0;
$("#contents ").animate({
top: t
}, 1000, function () {
// Animation complete.
});
}
function MoveDown() {
t -= 665;
with($("#contents")) {
//if(t < -clientHeight)
//t = -clientHeight;
if (t < -1330) t = -1330;
$("#contents").animate({
top: t
}, 1000, function () {
// Animation completed
});
}
}
Use this CSS to enable scrolling on your page:
body{overflow:scroll;}
OR
Scroll for a specific div:
.yourDivClass{overflow:scroll;}

How to halt jQuery function execution more than once while it's active?

I'm using this http://jsfiddle.net/CqAU2/ plugin for an image rotation, but if you click on the box in the fiddle more than once, it will continue rotating as many times as you clicked on it. What I'd like to do is take the click action into account only when the box isn't moving. How can that be done?
You can set a flag that 'locks' the action if it is still animating, and resets the locked flag after the same time as your animation duration (in your case 1000ms):
$(document).ready(function () {
var degree = 0;
var locked = false;
$(".big-ball").click(function () {
if (!locked) {
degree += 30;
$(this).jqrotate(degree, 1000);
locked = true;
setTimeout(function(){
locked = false;
},1000);
}
});
});
I've updated your Fiddle
Is this the result you wanted ?
http://jsfiddle.net/wq6qm/
I added stop() before calling the animation.
$(elem).stop().animate({...})
What does stop() do ?
When .stop() is called on an element, the currently-running animation
(if any) is immediately stopped.
More about stop here: http://api.jquery.com/stop/
i update your fiddle - i insert a control for prevent two or more click
$.fn.jqrotate = function (degrees, speed) {
if(typeof $.preventTwo !== "undefined" && $.preventTwo == false) return;
$.preventTwo = false;
return this.each(function () {
var elem = this;
elem.x = $(elem).data('rot')||0;
$(elem).animate({
x: degrees
}, {
duration : speed,
step: function( now, fx ) {
$(fx.elem).css({
'-webkit-transform' : 'rotate('+now+'deg)',
'-moz-transform' : 'rotate('+now+'deg)',
'-ms-transform' : 'rotate('+now+'deg)',
'-o-transform' : 'rotate('+now+'deg)',
'transform' : 'rotate('+now+'deg)'
}).data('rot', now);
},
complete : function(){
$.preventTwo = true;
}
});
});
};
$(document).ready(function () {
var degree = 0;
$(".big-ball").click(function () {
degree += 30;
$(this).jqrotate(degree, 2000);
});
});
byee...
http://jsfiddle.net/CqAU2/1/

How can I autoplay this javascript slider?

I have found this nice js slider that works by clicking on radio buttons, selecting the slides to view.
I'd like it to autoplay the slides, and give it a time for slides and transitions, but I'm honestly unsure where to put those values.
I've seen the other questions about similar problems, but couldn't find a proper answer to my problem. Help, please?
<script type="text/javascript">
$(document).ready(function () {
var showCaseItems = $('.show-case-item').hide();
var splashes = $('.splash').hide();
//get each image for each slide and set it as a background of the slide
// splashes.each(function () {
// var img = $(this).find('img');
// var imgSrc = img.attr('src');
// img.css('visibility', 'hidden');
// $(this).css({ 'background-image': 'url(' + imgSrc + ')', 'background-repeat': 'no-repeat' });
// });
splashes.eq(0).show();
showCaseItems.eq(0).show();
var prevIndex = -1;
var nextIndex = 0;
var currentIndex = 0;
$('#banner-pagination li a').click(function () {
nextIndex = parseInt($(this).attr('rel'));
if (nextIndex != currentIndex) {
$('#banner-pagination li a').html('<img src="assets/img/slidedot.png" alt="slide"/>');
$(this).html('<img src="assets/img/slidedot-active.png" alt="slide"/>');
currentIndex = nextIndex;
if (prevIndex < 0) prevIndex = 0;
splashes.eq(prevIndex).css({ opacity: 1 }).animate({ opacity: 0 }, 500, function () {
$(this).hide();
});
splashes.eq(nextIndex).show().css({ opacity: 0 }).animate({ opacity: 1 }, 500, function () { });
showCaseItems.eq(prevIndex).css({ opacity: 1 }).animate({ opacity: 0 }, 500, function () {
$(this).hide();
showCaseItems.eq(nextIndex).show().css({ opacity: 0 }).animate({ opacity: 1 }, 200, function () { });
});
prevIndex = nextIndex;
}
return false;
});
});
</script>
You can use jquery and setTimeout
setTimeout(function() {$('#banner-pagination li a').trigger('click');}, 1500);
this code will loop every 1.5 seconds and trigger a click on #banner-pagination li a
you can use the jquery trigger event and hit the radio button click event forcefully
$('#foo').trigger('click');
http://api.jquery.com/trigger/
setInterval(function()
{$('#banner-pagination li a[rel='+((currentIndex+1)%3)+']').trigger('click');},5000);
Thanks

Onload method is calling itself more than once on successive reloads to application (var image = new Image(), javascript issue)

I don't understand why onload method(see the code below) is calling itself more than once in IE8 and IE9 browsers on consecutive reloads.
I guess, onload method is fired more than once that is causing this image to render(appear) more than once in IE8,IE9. Below js code is written by my senior Front-Ender (he is using his own written js library for all .append(), anim(), ... methods). The code is working as expected in Firefox, Chrome but the image(html code) is rendering more than once while reloading with a IE8 or IE9 browser.
Some Quick Info:
waitingFor() - Periodically scans dom for matching elements,
mdiTog - The image that is appearing more than once..
How it works:
The div attribute Class="suggestions contextSuggesions" is inserted in the body element and contains an unordered list (ul, li, ul) that toggles between opacity 0 and 1 if you click on the image (mdiTog).
Below is the image of Mditog appearing more than once and it's appearance is random:
waitingFor('.viewport .homePage', function () {
var mdiTog = new Image();
mdiTog.onload = function () {
var $mdi = M$('.mdiTabs ul'),
$contextMenu = M$($body.append('<div class="suggestions contextSuggesions" style="display:none"></div>')),
$toggle = M$($mdi.append('<li class="mdiTog" style="display:none"></li>')),
visible = false,
active = false;
var hideCtx = function () {
if (visible) {
$contextMenu.anim('', {opacity: 100}, {opacity: 0}, 250, function () {
$contextMenu.css({display: 'none'});
});
visible = false;
}
};
$toggle.css({opacity: 0, display: 'inline-block'}).anim('', {opacity: 0}, {opacity: 100}, 1000).on('click', function () {
var togOS = $toggle.offset(),
menu = '';
M$('li', $mdi.get()).each(function (el, idx) {
if (idx > 1) {
menu += '<li rel="' + idx + '">' + $mdi.text(null, el) + '</li>';
}
});
$contextMenu.css({opacity: 0, display: 'block', top: togOS.top + 'px', left: (togOS.left - 20) + 'px'}).anim('', {opacity: 0}, {opacity: 100}, 400, function () {
visible = true;
}).html('<ul>' + menu + '<li class="uiUtil hr" onclick="ApolloUI.widgets.expose.show()">' + translate('previewAll') + '</li><li class="uiUtil" onclick="ApolloUI.mdi.closeAll()">' + translate('closeAll') + '</li></ul>');
});
$contextMenu.on('click', function (e) {
var target = $contextMenu.eventTarget(e);
if (target.tagName === 'LI' && target.className.indexOf('uiUtil') === -1) {
$contextMenu.fire('click', M$('.mdiTabs li').get(parseInt(target.getAttribute('rel'), 10)));
}
hideCtx();
}).on('mouseleave', function () {
active = false;
}).on('mouseenter', function () {
active = true;
});
setInterval(function () {
if (!active && visible) {
hideCtx();
}
}, 1000);
};
mdiTog.src = 'media/img/ico_16_context.png';
});
I do have to close this issue as soon as possible, so any suggestions/modifications/addition in this code to force onload to execute only once on even on several consecutive reloads in IE8/IE9 browsers are welcome.
If the onload fires twice, you should use a guard against executing the handler more than once:
var mdiTog = new Image();
var hasFired = false;
mdiTog.onload = function () {
if (hasFired)
return;
hasFired = true;
…
};
Or, if you're using a jQuery-like library, you could try the one event binding method:
var mdiTog = new Image();
M$(mdiTog).one("load", function () {
…
});

javascript 'over-clicking' bug

I have a bug in Javascript where I am animating the margin left property of a parent container to show its child divs in a sort of next/previous fashion. Problem is if clicking 'next' at a high frequency the if statement seems to be ignored (i.e. only works if click, wait for animation, then click again) :
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
//roll margin back to 0
}
An example can be seen on jsFiddle - http://jsfiddle.net/ZQg5V/
Any help would be appreciated.
Try the below code which will basically check if the container is being animated just return from the function.
Working demo
$next.click(function (e) {
e.preventDefault();
if($contain.is(":animated")){
return;
}
var marLeft = $contain.css('margin-left'),
$this = $(this);
if (marLeft === (-combinedWidth + (regWidth) + "px")) {
$contain.animate({
marginLeft: 0
}, function () {
$back.fadeOut('fast');
});
} else {
$back.fadeIn(function () {
$contain.animate({
marginLeft: "-=" + regWidth + "px"
});
});
}
if (marLeft > -combinedWidth) {
$contain.animate({
marginLeft: 0
});
}
});
Sometimes is better if you create a function to take care of the animation, instead of writting animation code on every event handler (next, back). Also, users won't have to wait for the animation to finish in order to go the nth page/box.
Maybe this will help you:
if (jQuery) {
var $next = $(".next"),
$back = $(".back"),
$box = $(".box"),
regWidth = $box.width(),
$contain = $(".wrap")
len = $box.length;
var combinedWidth = regWidth*len;
$contain.width(combinedWidth);
var currentBox = 0; // Keeps track of current box
var goTo = function(n) {
$contain.animate({
marginLeft: -n*regWidth
}, {
queue: false, // We don't want animations to queue
duration: 600
});
if (n == 0) $back.fadeOut('fast');
else $back.fadeIn('fast');
currentBox = n;
};
$next.click(function(e) {
e.preventDefault();
var go = currentBox + 1;
if (go >= len) go = 0; // Index based, instead of margin based...
goTo(go);
});
$back.click(function(e) {
e.preventDefault();
var go = currentBox - 1;
if (go <= 0) go = 0; //In case back is pressed while fading...
goTo(go);
});
}
Here's an updated version of your jsFiddle: http://jsfiddle.net/victmo/ZQg5V/5/
Cheers!
Use a variable to track if the animation is taking place. Pseudocode:
var animating = false;
function myAnimation() {
if (animating) return;
animating = true;
$(this).animate({what:'ever'}, function() {
animating = false;
});
}
Crude, but it should give you the idea.
Edit: Your current code works fine for me as well, even if I jam out on the button. On firefox.

Categories

Resources