I have <p> element:
<p id="news_title">Text goes here</p>
Which I have made to run text with help this JavaScript:
(function(){
var j = 0;
var el = document.getElementById("news_title");
var interval;
function runEngine(){
interval = setInterval(function(){
if (j===200){
j=-200;
}
el.style.left = j + "px";
j++;
},20);
}
window.onload = function(){
runEngine();
};
})();
Marked script working nicely, but I want to pause the text onmouseover and onmouseout let it continue running. Also, onclick I want to stop it for good.
el.onmouseover = function(){
clearInterval(interval);
}; // pausing , working nicely
el.onmouseout = function(){
runEngine();
}; // also working
The onclick is not working however. Even though I clear the interval, the onmouseout handler causes the text to run again. How can I prevent this?
On click, set a flag. Then check the flag in the onmouseout handler:
var clicked = false;
el.onclick = function() {
clicked = true;
};
el.onmouseout = function() {
if (!clicked) {
runEngine();
}
};
Related
I am new to web development and I love it.
But I've have encountered a problem and I can't figure it out.
When i lose my focus on my browser tab, my fade effect ,made for my images when they are change, is turns on multiple times. .
Another problem, i really want my images inside of my div element to be like : http://jsfiddle.net/eb51hxj1/ when i resize the browser.
<div class="divImage">
<img id="image"> </div>
<div>
My code is :
https://jsfiddle.net/a2bsarfb/
Make a new var that checks for the window focus. When the window focus is gone then just skip the rest of the code.
At the very top add a new var:
var lostFocus = false;
In the Caller function add:
if(lostFocus){ return false; }
So it will look like:
function Caller() {
var imag = ["https://i.ytimg.com/vi/tq0H6nQMdNk/maxresdefault.jpg", "https://i.ytimg.com/vi/4qVMnkF7W60/maxresdefault.jpg", "https://s-media-cache-ak0.pinimg.com/originals/52/1d/e6/521de6a52e774664745132156448f43b.jpg"];
var numarImagini = imag.length - 1;
var i = Math.floor((Math.random() * imag.length));
Rotate(imag[i], i);
i++;
setInterval(function() {
if(lostFocus){ return false; }
if (i > imag.length - 1) {
i = 0;
Rotate(imag[i], i);
i++;
} else {
Rotate(imag[i], i);
i++;
}
}, 2000)
}
And at the bottom add the event listeners:
window.onblur = function() { lostFocus = true; };
window.onfocus = function() { lostFocus = false; };
I have a set of divs in my HTML document and use jQuery to show them one by one after every 15000ms. I would also like to include some links inside some of the divs so I want to pause or delay the div on hover. Here is my script code. Can somebody show me how to pause on hover?
<script>
var ct = 0;
function showElem2() {
var length = $('.t1').length;
$('.t1').hide();
$('.info span').text(ct);
$('.t1').eq(ct).fadeIn(900);
(ct >= (length-1)) ? ct = 0: ct++;
setTimeout(showElem2, 1600);
}
$(document).ready(function(){
showElem2();
});
</script>
You can clear the timeout on mouseover and start it again on mouseout. I updated your code:
var ct = 0;
var myTimeout;
function showElem2() {
var length = $('.t1').length;
$('.t1').hide();
$('.info span').text(ct);
$('.t1').eq(ct).fadeIn(900);
(ct >= (length-1)) ? ct = 0: ct++;
myTimeout = setTimeout(showElem2, 1600);
}
$(document).ready(function(){
showElem2();
// $('div') is the container you want to attach the mouseover/mouseout event to.
$('div').hover(function() {
// mouseover
clearTimeout(myTimeout); // cancels the timeout
}, function() {
// mouseout
myTimeout = setTimeout(showElem2, 1600); // starts it again (or technically a new timeout)
});
});
Probably not the best solution code-wise, but the key here is clearTimeout() which let's you cancel a timeout set with setTimeout().
I believe you can tie the Timeout to a variable so you can cancel it on hover, then just reload the function on mouse out. This isn't tested but I think this should work:
:`
<script>
var ct = 0;
var timeoutvariable;
function showElem2() {
var length = $('.t1').length;
$('.t1').hide();
$('.info span').text(ct);
$('.t1').eq(ct).fadeIn(900);
$('.t1').eq(ct).hover(function(){ //on mouse enter
clearTimeout(timeoutvariable);
},
function(){ //on mouse leave
showElem2();
});
(ct >= (length-1)) ? ct = 0: ct++;
timeoutvariable = setTimeout(showElem2, 1600);
}
$(document).ready(function(){
showElem2();
});
</script>
`
I have a piece of code that hides an element on mouseout.
The code looks like this:
var myMouseOutFunction = function (event) {
setTimeout(function () {
$(".classToHide").hide();
$(".classToShow").show();
}, 200);
};
This produces a result very close to what I want to do. However, I want to wait the time on the timeout (in this case 200 ms) then check to see if my mouse is still "out" of the element. If it is, I want to do .hide() and .show() on the desired elements.
I want to do this because if a user slightly mouses out then quickly mouses back in, I don't want the elements to flicker (meaning: hide then show real quick) when the user just wants to see the element.
Assign the timeout's return value to a variable, then use clearTimeout in the onmouseover event.
Detailing Kolink answer
DEMO: http://jsfiddle.net/EpMQ2/1/
var timer = null;
element.onmouseout = function () {
timer = setTimeout(function () {
$(".classToHide").hide();
$(".classToShow").show();
}, 200);
}
element.onmouseover = function () {
clearTimeout(timer);
}
You should use mouseenter and mouseleave of jquery. mouseenter and mouseleave will get called only once.and use a flag if to check if mouseenter again called.
var isMouseEnter ;
var mouseLeaveFunction = function (event) {
isMouseEnter = false;
setTimeout(function () {
if(isMouseEnter ){ return;}
$(".classToHide").hide();
$(".classToShow").show();
}, 200);
};
var mouseEnterFunction = function(){
isMouseEnter = true;
}
Use a boolean flag:
var mustWait = true;
var myMouseOutFunction = function (event) {
setTimeout(function () {
if(mustWait){
mustWait = false;
}
else{
$(".classToHide").hide();
$(".classToShow").show();
mustWait = true;
}
}, 200);
};
I have an element on my page that I need to attach onclick and ondblclick event handlers to. When a single click happens, it should do something different than a double-click. When I first started trying to make this work, my head started spinning. Obviously, onclick will always fire when you double-click. So I tried using a timeout-based structure like this...
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
el.onclick = function() {
timer = setTimeout(function() { alert('Single'); }, 150);
}
el.ondblclick = function() {
clearTimeout(timer);
alert('Double');
}
}
But I got inconsistent results (using IE8). It would work properly alot of times, but sometimes I would get the "Single" alert two times.
Has anybody done this before? Is there a more effective way?
Like Matt, I had a much better experience when I increased the timeout value slightly. Also, to mitigate the problem of single click firing twice (which I was unable to reproduce with the higher timer anyway), I added a line to the single click handler:
el.onclick = function() {
if (timer) clearTimeout(timer);
timer = setTimeout(function() { alert('Single'); }, 250);
}
This way, if click is already set to fire, it will clear itself to avoid duplicate 'Single' alerts.
If you're getting 2 alerts, it would seem your threshold for detecing a double click is too small. Try increasing 150 to 300ms.
Also - I'm not sure that you are guaranteed the order in which click and dblclick are fired. So, when your dblclick gets fired, it clears out the first click event, but if it fires before the second 'click' event, this second event will still fire on its own, and you'll end up with both a double click event firing and a single click event firing.
I see two possible solutions to this potential problem:
1) Set another timeout for actually firing the double-click event. Mark in your code that the double click event is about to fire. Then, when the 2nd 'single click' event fires, it can check on this state, and say "oops, dbl click pending, so I'll do nothing"
2) The second option is to swap your target functions out based on click events. It might look something like this:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can stop it
if(firing)
return;
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
el.ondblclick = function() {
firingFunc = doubleClick;
// Now, when the original timeout of your single click finishes,
// firingFunc will be pointing to your doubleClick handler
}
}
Basically what is happening here is you let the original timeout you set continue. It will always call firingFunc(); The only thing that changes is what firingFunc() is actually pointing to. Once the double click is detected, it sets it to doubleClick. And then we always revert back to singleClick once the timeout expires.
We also have a "firing" variable in there so we know to intercept the 2nd single click event.
Another alternative is to ignore dblclick events entirely, and just detect it with the single clicks and the timer:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can set it to doubleClick
if(firing){
firingFunc = doubleClick;
return;
}
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
}
This is untested :)
Simple:
obj.onclick=function(e){
if(obj.timerID){
clearTimeout(obj.timerID);
obj.timerID=null;
console.log("double")
}
else{
obj.timerID=setTimeout(function(){
obj.timerID=null;
console.log("single")
},250)}
}//onclick
Small fix
if(typeof dbtimer != "undefined"){
dbclearTimeout(timer);
timer = undefined;
//double click
}else{
dbtimer = setTimeout(function() {
dbtimer = undefined;
//single click
}, 250);
}
, cellclick :
function(){
setTimeout(function(){
if (this.dblclickchk) return;
setTimeout(function(){
click event......
},100);
},500);
}
, celldblclick :
function(){
setTimeout(function(){
this.dblclickchk = true;
setTimeout(function(){
dblclick event.....
},100);
setTimeout(function(){
this.dblclickchk = false;
},3000);
},1);
}
I found by accident that this works (it's a case with Bing Maps):
pushpin.clickTimer = -1;
Microsoft.Maps.Events.addHandler(pushpin, 'click', (pushpin) {
return function () {
if (pushpin.clickTimer == -1) {
pushpin.clickTimer = setTimeout((function (pushpin) {
return function () {
alert('Single Clic!');
pushpin.clickTimer = -1;
// single click handle code here
}
}(pushpin)), 300);
}
}
}(pushpin)));
Microsoft.Maps.Events.addHandler(pushpin, 'dblclick', (function (pushpin) {
return function () {
alert('Double Click!');
clearTimeout(pushpin.clickTimer);
pushpin.clickTimer = -1;
// double click handle here
}
}(pushpin)));
It looks like the click event masks the dblclick event, and this usage is clearing it when we add a timeout. So, hopefully, this will work also with non Bing Maps cases, after a slight adaptation, but I didn't try it.
I've toggled click event to a node and I want to toggle a dbclick event to it as well. However it only triggers the click event when I dbclick on it.
So How do I set both events at the same time?
You have to do your "own" doubleclick detection
Something like that could work:
var clickedOnce = false;
var timer;
$("#test").bind("click", function(){
if (clickedOnce) {
run_on_double_click();
} else {
timer = setTimeout(function() {
run_on_simple_click(parameter);
}, 150);
clickedOnce = true;
}
});
function run_on_simple_click(parameter) {
alert(parameter);
alert("simpleclick");
clickedOnce = false;
}
function run_on_double_click() {
clickedOnce = false;
clearTimeout(timer);
alert("doubleclick");
}
Here is a working JSFiddle
For more information about what delay you should use for your timer, have a look here : How to use both onclick and ondblclick on an element?
$("#test-id").bind("click dblclick", function(){alert("hello")});
Works for both click and dblclick
EDIT --
I think its not possible. I was trying something like this.
$("#test").bind({
dblclick: function(){alert("Hii")},
mousedown: function(){alert("hello")}
});
But its not possible to reach double click without going through single click. I tried mouse down but it does not give any solution.
I pretty much used the same logic as Jeremy D.
However, in my case, it was more neat to solve this thing with anonymous functions, and a little slower double click timeout:
dblclick_timer = false
.on("click", function(d) {
// if double click timer is active, this click is the double click
if ( dblclick_timer )
{
clearTimeout(dblclick_timer)
dblclick_timer = false
// double click code code comes here
console.log("double click fired")
}
// otherwise, what to do after single click (double click has timed out)
else dblclick_timer = setTimeout( function(){
dblclick_timer = false
// single click code code comes here
console.log("single click fired")
}, 250)
})
you need to track double click and if its not a double click perform click action.
Try this
<p id="demo"></p>
<button id='btn'>Click and DoubleClick</button>
<script>
var doubleclick =false;
var clicktimeoutid = 0;
var dblclicktimeoutid = 0;
var clickcheck = function(e){
if(!clicktimeoutid)
clicktimeoutid = setTimeout(function(){
if(!doubleclick)
performclick(e);
clicktimeoutid =0;
},300);
}
var performclick =function(e){
document.getElementById("demo").innerHTML += 'click';
}
var performdblclick = function(e)
{
doubleclick = true;
document.getElementById("demo").innerHTML += 'dblclick';
dblclicktimeoutid = setTimeout(function(){doubleclick = false},800);
};
document.getElementById("btn").ondblclick = performdblclick;
document.getElementById("btn").onclick=clickcheck;
</script>
a slightly different approach - The actual click comparison happens later in the timeOut function, after a preset interval... till then we simply keep tab on the flags.
& with some simple modifications (click-counter instead of flags) it can also be extended to any number of rapid successive clicks (triple click, et al), limited by practicality.
var clicked = false,
dblClicked = false,
clickTimer;
function onClick(param){
console.log('Node clicked. param - ',param);
};
function onDoubleClick(param){
console.log('Node Double clicked. param - ',param);
};
function clickCheck(param){
if (!clicked){
clicked = true;
clickTimer = setTimeout(function(){
if(dblClicked){
onDoubleClick(param);
}
else if(clicked){
onClick(param);
}
clicked = false;
dblClicked = false;
clearTimeout(clickTimer);
},150);
} else {
dblClicked = true;
}
};