Simple Javascript button 2 in 1 - javascript

Hi im just having some issues,
Im trying to make this text blink with just one button click
So Click ON
And also Click Acts as OFF ( If clicks value is set to on which is 1 )
Im pretty new to JS any help would be appreciated
var Blinker = {
interval: null,
start: function() {
if (this.interval) return;
this.interval = setInterval(function() {
$('#demo').toggle();
}, 250);
},
stop: function() {
clearInterval(this.interval);
$('#demo').show();
this.interval = null;
}
}
//Initialize blink status.
var blinkStatus = 1;
//Check if status is changed, and run/stop blinking.
setInterval(function() {
if (blinkStatus == 1) {
Blinker.start();
}
else {
Blinker.stop();
}
}, 250);
$('#start').on('click', function() {
blinkStatus = 1;
});
$('#stop').on('click', function() {
blinkStatus = 0;
});
<h1 id="demo">PAUSE</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>

Try this code. This toggles blinking with a single button.
HTML:
<div class="text-container">
<h1 id="demo">PAUSE</h1>
</div>
<button id="toggle-button">Start</button>
CSS:
.hide {
display: none;
}
.text-container {
height: 17px;
}
JS:
var Blinker = {
interval: null,
start: function() {
if (this.interval) return;
this.interval = setInterval(function() {
$('#demo').toggleClass('hide');
}, 250);
},
stop: function() {
clearInterval(this.interval);
$('#demo').removeClass('hide');
this.interval = null;
}
}
//Initialize blink status.
var blinkStatus = 0;
//Check if status is changed, and run/stop blinking.
setInterval(function() {
if (blinkStatus == 1) {
$('#toggle-button').text('Stop');
Blinker.start();
}
else {
$('#toggle-button').text('Start');
Blinker.stop();
}
}, 250);
$('#toggle-button').on('click', function() {
if (blinkStatus) {
blinkStatus = 0;
} else {
blinkStatus = 1;
}
});

I've edited your code slightly, basing on your request on the comment.
//Initialize blink status.
var blinkStatus = false;
//Check if status is changed, and run/stop blinking.
var blinker, visibility;
$('#button').on('click', function() {
blinkStatus = !blinkStatus;
if(blinkStatus){
blinker = setInterval(function() {
visibility = $("#demo").css('visibility');
if(visibility == 'hidden'){
$("#demo").css('visibility', 'visible');
}else{
$("#demo").css('visibility', 'hidden');
}
}, 500);
$("#button").text('Stop');
}else{
clearInterval(blinker);
$("#button").text('Start');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="demo">PAUSE</h1>
<button id="button">Start</button>

Related

Resume a function after clearInterval

I have this code:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer);
}
});
$el.mouseout({
timer;
});
});
I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?
Thank you.
There are two ways:
Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."
Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.
Example of #1:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
suspend = false; // The flag
var timer = setInterval(function() {
if (!suspend) { // Check it
$el.removeClass("current").eq(++c % tot).addClass("current");
}
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
suspend = true; // Set it
},
mouseleave: function(e) {
suspend = false; // Clear it
}
});
});
Example of #2:
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0,
timer = 0;
// Move this to a reusable function
var intervalHandler = function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
};
// Probably best to encapsulate the logic for starting it rather
// than repeating that logic
var startInterval = function() {
timer = setInterval(intervalHandler, 3000);
};
// Initial timer
startInterval();
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
clearInterval(timer); // Stop it
}
mouseleave: function(e) {
startInterval(); // Start it
}
});
});
Checkout these prototypes:
//Initializable
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function PeriodicJobHandler(params) {
Initializable.call(this, params);
this.initialize("timeout", 1000, true);
var getTimeout = function() {
return params.timeout;
};
var jobs = [];
function Job(params) {
//expects params.job() function
Initializable.call(this, params);
this.initialize("timeout", getTimeout(), true);
this.initialize("instant", false);
var intervalID = undefined;
this.start = function() {
if (intervalID !== undefined) {
return;
}
if (this.instant) {
params.job(true);
}
intervalID = setInterval(function() {
params.job(false);
}, params.timeout);
};
this.stop = function() {
clearInterval(intervalID);
intervalID = undefined;
};
}
this.addJob = function(params) {
jobs.push(new Job(params));
return jobs.length - 1;
};
this.removeJob = function(index) {
jobs[index].stop();
jobs.splice(index, 1);
};
this.startJob = function(index) {
jobs[index].start();
};
this.stopJob = function(index) {
jobs[index].stop();
};
}
Initializable simplifies member initialization, while PeriodicJobHandler is able to manage jobs in a periodic fashion. Now, let's use it practically:
var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
instant: true,
job: function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}
});
jQuery(function($) { // DOM is ready
var $el = $("header tr"),
tot = $el.length,
c = 0;
var timer = setInterval(function() {
$el.removeClass("current").eq(++c % tot).addClass("current");
}, 3000);
$el.first().addClass("current");
$el.on({
mouseenter: function(e) {
jobIndex.stop();
}
});
$el.mouseout({
jobIndex.start();
});
});
With Javascript, it is much easy and efficient.
You can change the interval in setInterval function.
It is checking whether suspend variable is false or true, here suspend variable is setting to true, if mouseEnter function is called and set to false if mouseLeave function is called.
var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);
function update() {
if (suspend == false) {
var dispalyedMsg = '';
dispalyedMsg = displayMsg.substring(i, displayMsg.length);
dispalyedMsg += ' ';
dispalyedMsg += displayMsg.substring(0, i);
document.getElementById('msg').innerHTML = dispalyedMsg;
i++;
if (i > displayMsg.length) {
i = 0;
}
}
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);
function mouseEnter() {
suspend = true;
}
function mouseLeave() {
suspend = false;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#msg {
width: 680px;
height: 100px;
border: 1px solid #ccc;
padding-left: 15px;
}
</style>
</head>
<body>
<div id="msg">
Today is only 15% discount. Hurry up to grab. Sale will end sooooooooooooon!!!!
</div>
<div id="output"></div>
<script src="marquee.js"></script>
</body>
</html>

setTimeout with jQuery.hover() overlapping

I've got an effect I want triggered one second after page load, then subsequently every 3 seconds (on repeat). When the user hovers over an element (#hover), the effect pauses (temporarily). When they stop hovering over it, the effect resumes after 2 seconds.
I'm having a lot of trouble with overlapping sounds and animations, particularly when I hover and then unhover over the element quickly. What's wrong with my code? (Fiddle)
var test;
function hoverTest(arg) {
if (arg == 'stop') {
clearTimeout(test);
}
if (arg == 'start') {
playSound();
$('#hover').transition({
opacity: 0,
duration: 1000,
complete: function() {
$('#hover').transition({
opacity: 1,
duration: 1000,
complete: function() {
test = setTimeout(function() { hoverTest('start'); }, 3000);
}
});
}
});
}
}
$('#hover').hover(function() {
hoverTest('stop');
}, function() {
setTimeout(function() {
hoverTest('start');
}, 2000);
});
function playSound() {
var sound = new Audio('sound.mp3');
sound.play();
}
setTimeout(function() {
hoverTest('start');
}, 1000);
copy paste this in a file and run that html file.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#hover {
width: 100px;
height: 100px;
background: red;
}
</style>
<div id="hover"></div>
<script type="text/javascript">
var interval = null;
var hoverTest = function(method){
playSound();
$("#hover").fadeOut(1000, function() {
$(this).fadeIn(1000);
});
}
var playSound =function() {
var sound = new Audio('http://www.sounddogs.com/previews/25/mp3/306470_SOUNDDOGS__an.mp3');
sound.play();
}
$(document).ready(function(){
interval = setInterval('hoverTest()',3000);
$("#hover").mouseenter(function(){
clearInterval(interval);
}).mouseleave(function(){
interval = setInterval('hoverTest()',3000);
})
})
</script>
Try adding "clearTimeout(test);" the first thing in the hoverTest function.
eg:
var test;
function hoverTest(arg) {
clearTimeout(test);
if (arg == 'stop') {
clearTimeout(test);
}
if (arg == 'start') {
playSound();
$('#hover').transition({
opacity: 0,
duration: 1000,
complete: function() {
$('#hover').transition({
opacity: 1,
duration: 1000,
complete: function() {
test = setTimeout(function() { hoverTest('start'); }, 3000);
}
});
}
});
}
}
Try this: (clear the timer before starting)
$('#hover').hover(function() {
hoverTest('stop');
}, function() {
clearTimeout(test);
setTimeout(function() {
hoverTest('start');
}, 2000);
});

I was trying to make a news ticker. But there's an error when mouse leaves after hover

After Mouse Leave the ticker starts to move at a very high speed. Don't know what's the error.
Javascript:
$('#tick2').html($('#tick').html());
var temp=0,intervalId=0;
$('#tick li').each(function() {
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick').css({'width':temp+40, 'margin-left':'20px'});
temp=0;
$('#tick2 li').each(function(){
var offset=$(this).offset();
var offsetLeft=offset.left;
$(this).css({'left':offsetLeft+temp});
temp=$(this).width()+temp+10;
});
$('#tick2').css({'width':temp+40,'margin-left':temp+40});
function abc(a,b) {
$('#outer').mouseenter(function() { window.clearInterval(intervalId);intervalId=0; });
$('#outer').mouseleave(function() { start(); })
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
start();
You can check the working demo here : http://jsfiddle.net/mstoic/juJK2/
Well, you nearly blew up my browser! Can you try this instead:
function abc(a,b) {
var marginLefta=(parseInt($("#"+a).css('marginLeft')));
var marginLeftb=(parseInt($("#"+b).css('marginLeft')));
if((-marginLefta<=$("#"+a).width())&&(-marginLefta<=$("#"+a).width())){
$("#"+a).css({'margin-left':(marginLefta-1)+'px'});
} else {
$("#"+a).css({'margin-left':temp});
}
if((-marginLeftb<=$("#"+b).width())){
$("#"+b).css({'margin-left':(marginLeftb-1)+'px'});
} else {
$("#"+b).css({'margin-left':temp});
}
}
function start() { intervalId = window.setInterval(function() { abc('tick','tick2'); }, 10) }
$(function(){
$('#outer').mouseenter(function() { window.clearInterval(intervalId); });
$('#outer').mouseleave(function() { start(); })
start();
});
Working fiddle: http://jsfiddle.net/juJK2/1/
You should only bind your event handlers once, not every time you enter abc();

How to stop document.ready from exection in jquery

My query in the below code is --- I used a function slider in document.ready.Now my query is that when I click 'dot1' The function slider in the document.ready to stop execute until the function is called again. How to achieve this?Can anyone help me.....
Thanking you in advance.
here is my code:
var imgValue;
var value;
var flag;
function ClickEvent() {
$('span[id^="dot"]').click(function (event) {
event.stopPropagation();
var Clickid = $(event.target)[0].id;
$('.image1').css('display', 'none');
$('.innerdiv').css('display', 'none');
switch (Clickid) {
case 'dot1':
{
debugger;
SliderTimer = null;
clearInterval(SliderTimer);
flag = 0;
value = 1;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot1 Clicked");
break;
}
case 'dot2':
{
//alert("dot2 Clciked");
//setTimeout(SlideImage(), 5000);
value = 2;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot2 Clicked");
break;
}
case 'dot3':
{
//alert("dot3 Clicked");
//setTimeout(SlideImage(), 5000);
value = 3;
ImageLoad(value);
//setTimeout(SlideImage(), 150000);
//alert("dot3 Clicked");
break;
}
}
});
}
function ImageLoad(count) {
$('* span').css('background-color', '#ccc');
$('.Dots #dot' + count).delay(4500).css('background-color', "Black");
$('.image #img' + count).show('fade', { direction: 'right' }, 1000);
$('.image #indiv' + count).delay(1500).show('fade', 1000);
$('.image #indiv' + count).delay(2500).hide('fade', { direction: 'left' }, 1000);
$('.image #img' + count).delay(4500).hide('fade', { direction: 'left' }, 1000);
}
function LoadPage() {
$('.image #img1').show('fade', 1000);
$('* span').css('background-color', '#ccc');
$('.Dots #dot1').css('background-color', 'Black');
}
$(document).ready(function Slider() {
var sc = $('.image img').size();
LoadPage();
value = 1;
setInterval(SliderTimer, 5000);
ClickEvent();
});
var SliderTimer = function SliderImage() {
var sc = $('.image img').size();
ImageLoad(value);
if (value == sc) {
value = 1;
}
else {
value += 1;
}
}
</script>
Use clearInterval :
var timer = setInterval(function() { ... }, 666);
...
$('#butt').click(function(){
clearInterval(timer);
});
EDIT : here's how your code would look :
var sliderTimer;
function ClickEvent() {
...
switch (Clickid) {
case 'dot1':
{
clearInterval(sliderTimer);
...
}
...
$(document).ready(function Slider() {
...
sliderTimer = setInterval(SliderTimer, 5000);
ClickEvent();
});
function SliderImage() {
var sc = $('.image img').size();
ImageLoad(value);
if (value == sc) {
value = 1;
}
else {
value += 1;
}
}

Why isn't .is(":hover") working?

I have this code to fade out some stuff on a page after you don't move your mouse for a second or so:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(":hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e) {
idleTime = 0;
$('.fade-outs').fadeIn();
});
But, I am getting the following error with $('.fade-outs').is(":hover"); part:
Error: Syntax error, unrecognized expression: hover [http://localhost:5545/assets/js/jquery.min.js:3]
Does anyone know why I am getting this error?
I would try something like this instead:
var idleTimer;
function startTimer() {
stopTimer();
idleTimer = setInterval(function() {
$('.fade-outs').stop().fadeOut();
}, 1000);
}
function stopTimer() {
idleTimer && clearInterval(idleTimer);
}
$(document).on('mousemove', startTimer);
$('.fade-outs').on({
mouseleave: startTimer,
mouseenter: stopTimer,
mousemove: function(e) {
e.stopPropagation();
}
});​
Demo: http://jsfiddle.net/Blender/urzug/4/
Try changing it to this:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(".hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e){
idleTime = 0;
$('.fade-outs').fadeIn();
});
$('.fade-outs').hover(funciton() { $(this).toggleClass('hover') });

Categories

Resources