Fade effect refresh on lost focus mutiple times - javascript

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; };

Related

div with an id wont accept any event handlers JavaScript. No Jquery

Im trying to pause a timed slideshow when you're hovering over a div
<div id="play_slide" onMouseOver="clearTimeout(playTime)"></div>
If i put onMouseOver="clearTimeout(playTime)" inside an li on the page, it'll pause, so I know my code is correct, it just wont work on the div! Also if i get rid of the id, it will alert when i put an alert function into an event handler
This is the js.
var playTime;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
you can see this here: www.nicktaylordesigns.com/work.html
I would do it like this:
( and no inline script... just <div id="play_slide">Something</div> )
var playTime;
var indexPlay = 0;
var slideElement;
window.onload = function () {
slideElement = document.getElementById("play_slide");
slideElement.addEventListener('mouseenter', function () {
console.log('stop');
clearTimeout(playTime);
});
slideElement.addEventListener('mouseleave', function () {
console.log('continue');
playTime = setTimeout(playSlide, 2500);
});
playSlide();
}
function playSlide() {
var slideshow = slideElement.style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if (indexPlay > images.length - 1) {
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/" + images[indexPlay] + ".png')";
playTime = setTimeout(playSlide, 2500);
}
Fiddle
This issue is related to the script loading. Your script gets loaded after the DOM is processed so function doesn't get attached to the event.
If you are using jQuery then you can use below code.
$(function () {
$("#play_slide").mouseover(function(){
var playTime = 33;
clearTimeout(playTime);
});
});
If you don't want to use JQuery then you can do the same thing in JavaScript as below.
window.onload = function(){
document.getElementById("play_slide").onmouseover = function(){
var playTime = 33;
clearTimeout(playTime);
};
}
I got it! the div tag was somehow broken, I coded a div around it and gave it the event handlers and a class. That worked, then i simply changed the class to an id and got rid of the original div. Idk what was going on but it works now. Thanks for your suggestions!
Can you try this,
<div id="play_slide" onmouseover="StopSlide();">Stop</div>
<script>
var playTime;
var indexPlay;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
function StopSlide(){
window.clearTimeout(playTime);
}
playSlide();
</script>

Javascript track when element became visible?

I have different controls on screen and hide and show them asynchronously. Is there any way to track when an element becomes actually visible on the screen? I actually want to get a callback when that happens and move the focus on that element!
try this
var trk = new Array("element1","element2","element3"); // add elements IDS whom you want to track
window.onload = function(){
track();
}
function track()
{
var ele;
for(var i=0;i<trk.length;i++)
{
ele= document.getElementById(trk[i]);
if(ele)
{
if(ele.style.display!="none")
{
// do something
}
}
}
setTimeout(function(){track();},1);
}
The only way that I can think of is to have a setInterval method which checks of the element.style.display!=="none", or whatever other method you used to hide and show the element.
Something like:
var myInterval = setInterval(function()
{
var element = document.getElementByID("SomeElement");
if( element.style.display!=="none" || element.style.visibility!=="hidden")
{
//exit the interval
clearInterval(myInterval);
doSomeFunction();
}
}, 20);

Fade-out controls when there's no keyboard/mouse input

Based on this script I found on Stack Overflow, I tried adapting it to fade out an editor panel on a HTML page. Fading out works fine, but I'd like limit the fade-out from being triggered.
What I hope to accomplish is to prevent the fade-out whenever the mouse is over the editor panel (and child controls) or when there's keyboard activity in one of the input children.
var i = null;
// this part is working
$("#my-canvas").mousemove(function() {
clearTimeout(i);
$("#panel,#btn-panel-toggle,#fps").fadeIn(200);
var i = setTimeout('$("#panel,#btn-panel-toggle,#fps").fadeOut(800);', 3000);
})
// this part is not working
$("#panel").mouseover(function() {
clearTimeout(i);
})
For a live example, please check out this jsFiddle.
Two independent variables are needed here to indicate, whether the input#sc-url is focused and div#panel is hovered by mouse or not. Then you can handle the timer with these functions:
$(function () {
var t = null; //timer
var is_url_focused = false, is_panel_hovered = false;
var panel = $('#panel');
function hide_panel(){
if (t) {
clearTimeout(t);
}
t = setTimeout(function(){
if (is_url_focused || is_panel_hovered) {
return;
}
panel.stop().animate({
opacity:0
},800, function(){
panel.hide(); // == diplay:none
});
},2000);
}
function show_panel(){
panel.show().stop().animate({
opacity:1
},800);
}
$('#my-canvas').mouseenter(function(){
show_panel();
}).mouseleave(function(){
hide_panel();
});
$('#panel').hover(function(){
is_panel_hovered = true;
show_panel();
}, function(){
is_panel_hovered = false;
hide_panel();
});
$('#sc-url').focus(function(){
is_url_focused = true;
show_panel();
}).blur(function(){
is_url_focused = false;
hide_panel();
});
$('#btn-panel-toggle').click(function(){
if (panel.is(':hidden')) {
panel.css('opacity',1).show();
} else {
panel.css('opacity',0).hide();
}
});
});
http://jsfiddle.net/w9dv4/3/

Running text: Pause, Stop

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();
}
};

Repeating code block problem

I have the following code in a jQuery JavaScript document running on a page (THIS IS CURRENT):
$(window).resize(function(){
detectscreen();
});
function windowWidth() {
if(!window.innerWidth) {
// user is being a git, using ie
return document.documentElement.clientWidth;
} else {
return window.innerWidth;
}}
gearsExists = false;
function detectscreen() {
shouldExist = windowWidth() >= 1300;
if (shouldExist != gearsExists) {
if (shouldExist) {
$('body').append('<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(function() {
$(this).stop().fadeTo(500,1);
}, function() {
$(this).stop().fadeTo(500,0);
});
} else {
$('#gearsfloat').remove();
$('#clickGoTop').remove();
}
gearsExists = shouldExist;
}
}
This code is from my previous question, branched here simply because I think it is related.
The problem here is that the beginning is fine: it is displayed. However, if the screen is resized to less than 1300, it disappears; still good.
Now I make the window again larger than 1300. Suddenly the gear element is doubled. Another screen squish and largen and BAM, there's three now. Do this several times and it quickly adds up.
How can I stop this?
If you hook any code in resize event, make sure that your code doesn't resize the window again. Otherwise, resize event will fire again and your code will go in infinite loop.
Also, in your code, you are not using the global gearsExists variable. Remove the 'var' at the bottom of the method to use the global variable.
function detectscreen() {
// Your original code
//var gearsExists = shouldExist; //This code will create new local variable.
gearsExists = shouldExist;
}
}
EDIT: Here's what I would do:
//We will add only one variable to the global scope.
var screenManager = function()
{
var pub = {};
var inResizeHandler = false;
pub.getWindowWidth = function()
{
return window.innerWidth || document.documentElement.clientWidth;
};
pub.manage = function()
{
//if we are already in the resize handler, don't do anything.
if(inResizeHandler)
return;
inResizeHandler = true;
if(pub.getWindowWidth() < 1300)
{
$('#gearsfloat').remove();
//You don't have to remove clickGoTop because it is part of gearsfloat.
inResizeHandler = false;
return;
}
if($('#gearsfloat').length > 0)
{
inResizeHandler = false;
return false;
}
$('body').append('<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(
function() {$(this).stop().fadeTo(500,1);},
function() {$(this).stop().fadeTo(500,0);
});
inResizeHandler = false;
};
pub.init = function()
{
$(window).resize(pub.manage);
};
return pub;
}();
$(document).ready( function() { screenManager.init(); } );
EDIT:
Final working version:
http://jsbin.com/ufipu
Code:
http://jsbin.com/ufipu/edit
Haha! After a while, I decided to ignore everything said by everyone else for a while (sorry) and try to see if I could figure it out myself, and I did!
Thanks to SolutionYogi for all the help, but the code he gave me was out of my expertise; it was impossible to debug. My solution is not as pretty as his (if you can help optimize, please do), but it works:
function WinWidth() {
// check width of content
if(!window.innerWidth) {
// you git, how dare you use ie
return document.documentElement.clientWidth;
} else {
return window.innerWidth;
}
};
function gearsAction() {
if(WinWidth() >= 1300) {
$('body').append(
'<div id="gearsfloat"></div>');
$('#clickGoTop').fadeTo(0,0);
$('#clickGoTop').hover(
function() {$(this).stop().fadeTo(500,1);},
function() {$(this).stop().fadeTo(500,0);});
};
};
$(document).ready(function() {
gearsAction();
});
$(window).resize(function() {
$('#gearsfloat').remove();
gearsAction();
});

Categories

Resources