I need to send an alert to the user every time the z-index equals 2. Unfortunately it only occurs onload, or ready...whatever...
heres the html
<div id='slides'>
<img class='sliderImg' src='img.jpg'>
<img class='sliderImg' src='img.jpg'>
<img class='sliderImg' src='img.jpg'>
</div>
and the Javascript
document.ready=function(){
var theImage=$('.sliderImg')[0];
if(theImage.style.zIndex==2){
alert(theImage.style.zIndex);
}
}
You have two choices:
1) Run a timer and call your function periodically, using setInterval or setTimeout
2) Listen for DOM changes, then run your function.
You can use setInterval function after t time to check the z-index like this :
window.setInterval(function(){
var theImage=$('.sliderImg')[0];
if(theImage.style.zIndex==2){
alert(theImage.style.zIndex);
}
},10000);
It will be called on every 10 seconds.
jQuery style :
document.ready = function(){
checkZIndexOfImage(zIndex);
window.setInterval(checkZIndexOfImage, 10000);
}
function checkZIndexOfImage(zIndex) {
var theImage=$('.sliderImg').first(); //or $('.sliderImg').eq(0)
var tempzIndex = theImage.style('z-index');
tempzIndex = parseIng(zIndex);
if (isNaN(tempzIndex)) { //Let's check z-index is number
tempzIndex = 0;
}
if(tempIndex === zIndex){
alert(tempzIndex );
}
}
Related
I'm trying to build a website that allows me to see my screen.
But I don't know how I can get the image it's displaying to constantly change.Thanks for the help
Here is my current JS code:
window.onload = refreshBlock();
function refreshBlock()
{
document.getElementById("video").innerHTML = "<img src='image1.jpg' width='1000' height='500'></img>"
setInterval("refreshBlock();",100);
}
First of all, there are two different built-in JavaScript functions to execute some code with a delay.
setInterval() will execute the code every X milliseconds automatically, while
setTimeout() will execute the code once after X milliseconds
What you're currently doing is calling refreshBlock() every 100 milliseconds, and in that function generating a new interval, so after a few iterations, you end up with hundreds of intervals growing exponentially.
You can either put setInterval() outside of the callback function or call setTimeout inside of the callback function to avoid this.
In addition to that,
window.onload = refreshBlock();
is not doing what you think it's doing. By calling the function via (), you are setting window.onload to the result of the execution of refreshBlock(). By that time, any elements referenced inside the function might not yet be in the DOM. Instead, you want to set merely the function reference as the onload callback on the window object:
window.onload = refreshBlock;
I suggest to only change the SRC of the image instead of the whole tag:
<html>
<body>
<div id="video">
<img src='image1.jpg' width='1000' height='500' id="image"></img>
</div>
<script>
window.onload = refreshBlock;
function refreshBlock()
{
document.getElementById("image").src="image4.jpg";
setTimeout("refreshBlock",1000);
}
</script>
</body>
</html>
Also "setTimeout" is more what you need than "setInterval".
you want o change the images constantly this is a simple example for three images it will keep switching between these images constantly so by another meaning the images will keep changing there are many example i have but i believe this is the easiest one
refreshBlock();
function refreshBlock() {
var x = 0;
//image 1
document.getElementById("v").innerHTML =" <img src='image1.jpg' width='1000' height='500'></img>";
setInterval(function() {
if (x == 0) {
//image 2
document.getElementById("v").innerHTML =" <img src='image2.jpg' width='1000' height='500'></img>";
} else if (x == 1) {
//image 3
document.getElementById("v").innerHTML =" <img src='image3.jpg' width='1000' height='500'></img>";
}
x++;
if (x == 2) {
x = 0;
}
}, 5000);
}
You don't need a window.onload event to start your updates. The code below start as soon as the page is loaded, loops every 100ms and terminates when you close or reload the page.
let handle = setInterval( () => {
document.getElementById("video").innerHTML = "<img src='image1.jpg' width='1000' height='500'></img>"
}, 100);
To terminate the setInterval loop at any time you can use clearInterval(handle)
I want to create a timer that will add or remove divs ( inline divs ) based on time function in Javascript or Jquery.
E.g With each second i want to add a div or remove a div.
Can i get some ideas on this?
<html>
<head>
<title>Testing</title>
<script>
var i = 0;
var myVar=setInterval(function () {myTimer()}, 1000);
function myTimer()
{
document.getElementById('Container').innerHTML += "<div id='"+i+"'>This is the Div with New ID 'i'</div>";
i++;
}
</script>
</head>
<body>
<div id='Container'>
</div>
</body>
</html>
This Should Create a DIV each second inside the Div with id 'Container'
Use setInterval.
var diff = 1000, // how long between adds in milliseconds
totalTime = 0, // how long we have run
maxTime = 1000*60*60*5, // how long we want to run
interval = setInterval(function() {
$(".parentDiv").append($("<div>new div</div>"));
totalTime += diff; // keep track of all of our time
if (totalTime >= maxTime) {
clearInterval(interval);
}
},diff);
Note that the time is in milliseconds.
And to get rid of it
clearInterval(interval);
Beware that it will keep running, and if any of your actions take too long or slow down, you could find yourself with quite the mess stumbling over each other.
You can make use of setTimeout(function, mili seconds)
var testTimer;
function timer()
{
// Do your stuff
testTimer = setTimeout("timer()",1000);
}
This will call your timer function every one second. and you can do your stuff in this function
To stop this timer function you can do
window.clearTimeout(testTimer);
I need, that some images (for example random 5 - 8 of them) on background will automatically change for another one image (for example after 10 sec, something like that example-link but automatically, not on hover).
$('.fader').hover(function() {
$(this).find("img").fadeToggle();
});
I made a JSFiddle DEMO.. Maybe it helps you.
It's pretty simple, that's the function that I execute in setInterval
var $imgs = $(".fader").find("img"),
i = 0;
function changeImage(){
var next = (++i % $imgs.length);
$($imgs.get(next - 1)).fadeOut(500);
$($imgs.get(next)).fadeIn(500);
}
var interval = setInterval(changeImage, 2000);
Hope it help..
You can use setInterval to run a function every so often, then inside it have your image changing function
//global variable
var bgImg = 1;
//runs every second
window.setInterval(function(){
yourFunction();
}, 10000);
//changes background image
function yourFunction () {
++bgImg;
if(bgImg === 4){
bgImg = 1;
}
if(bgImg === 1){
$('#element').css("background-image","URL('imgs/image1.jpg')");
}
if(bgImg === 2){
$('#element').css("background-image","URL('imgs/image3.jpg')");
}
if(bgImg === 3){
$('#element').css("background-image","URL('imgs/image3.jpg')");
}
}
You can always add some more jquery to fade the image in out or something smoother than a plain switch
is this what you want?
Use BX slider.
http://jsfiddle.net/writetobhuwan/Xm2Be/393/
JS is as simple as this..
$(document).ready(function(){
$('.bxslider').bxSlider();
});
I have multiple paragraphs in an html-file that should show a dynamic countdown.
So I made a Countdown function in javascript, that returns the remaining time every time it is called. Unfortunately, I don't know how to call this function every second in the html file. Can you please help me out?
This is how my html file looks like:
EDIT, I have many countdown-paragraphs in my html file!:
<p class="countdown"><script>document.write(CountdownAnzeigen('2012-07-16 12:20:00'));</script></p>
<p class="countdown"><script>document.write(CountdownAnzeigen('2012-08-10 10:10:00'));</script></p>
...
The javascript function looks like:
function CountdownAnzeigen(end_datetime){
var Now = new Date();
var Countdown = Date.parse(end_datetime);
var CountdownText = Countdown.getTime()-Now.getTime();
return CountdownText;
}
setInterval(function() {
CountdownAnzeigen('2012-07-16 12:20:00');
}, 1000);
The setInterval(foobar, x) function is used to run a function foobar every x milliseconds.
Note that foobar can either be a function to be run or a string which will be interpreted as a Javascript, but I believe its accepted that using the string methodology is bad practice.
See the MDN setInterval docs.
(See also setInterval's sister method setTimeout's documentation.)
Use data- attributes to associate a target time with each element:
<p class="countdown" data-target-time="2012-07-06 12:20:00"></p>
<p class="countdown" data-target-time="2012-08-10 10:10:00"></p>
Then use a single setInterval function to fill each countdown-classed element with the result of the countdown function for its related time data:
setTimeout(function() {
var countdowns = document.getElementsByClassName("countdown");
for(var i=0; i < countdowns.length; ++i) {
var cd = countdowns[i];
cd.innerHTML = CountdownAnzeigen(cd.getAttribute("data-target-time"));
}
}, 1000);
This creates completely valid HTML5 and still functions correctly in older browsers.
Besides all answers how to use setInterval(), nobody explained, how to get the result into the paragraph. :)
So again, call you function like this:
setInterval(function() { CountdownAnzeigen('2012-07-16 12:20:00'); }, 1000);
And update the function:
// remove return value
return CountdownText;
// and replace it with this
document.getElementById('countdown').innerHTML = CountdownText;
Finally change your HTML to this:
<p class="countdown" id="countdown"></p>
If you don't use any "onload"-handler, place all your JavaScript below the paragraph and call the function once manually, to have the start time immediately and not the first time after one second.
EDIT
If you have multiple paragraphs you could do it like this:
<p class="countdown" id="countdown_1"></p>
<p class="countdown" id="countdown_2"></p>
<script>
setInterval(function() { CountdownAnzeigen('countdown_1', '2012-07-16 12:20:00'); }, 1000)
setInterval(function() { CountdownAnzeigen('countdown_2', '2012-07-16 12:20:00'); }, 500)
</script>
And update the function to:
document.getElementById(id).innerHTML = a;
Where ìd is a new parameter from the function call.
You can call function periodically also via the setTimeout().
Example:
javascript
function CountdownAnzeigen(countdown){
document.getElementById('countdown').innerHTML = countdown--;
if (countdown>0) {
window.setTimeout(function(){CountdownAnzeigen(countdown);}, 1000);
} else { alert('The End');}
}
html
<input type="button" value="count down" onclick="CountdownAnzeigen(10)"/>
<div id="countdown"></div>
Basically I need the thumbnails to rotate every time the user hovers over an image. Here is my failed attempt:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('img').hover(function() {
theImage = $(this).attr('id');
otherImages = $(this).attr('class').split('#');
rotateThumbs(otherImages, theImage);
}, function() {
//
});
});
function rotateThumbs(otherImages, theImage) {
for (i=0; i < otherImages.length; i++) {
setInterval($('#'+theImage).attr('src', otherImages[i]), 1000);
}
}
</script>
<img id="myImage" src="http://www.google.com/images/logos/ps_logo2.png" class="http://www.google.com/images/logos/ps_logo2.png#http://l.yimg.com/a/i/ww/met/yahoo_logo_us_061509.png#http://dogandcat.com/images/cat2.jpg" width="174" height="130" />
Does anyone know how this may be accomplished?
Some issues here.
setInterval requires a function reference as it's first argument, but you are executing code that returns a jQuery object.
setInterval executes the first function repeatedly at the specified interval. Is that what you are trying to do? Swap images every second?
Depending on how you correct the first issue, you could run into an issue where i is otherImages.length and thus the src is set to undefined.
Assuming you worked around issue 3, you will have the problem that the image swaps will happen imperceptibly fast and it will appear as though the last image is always displayed.
Instead, don't use a loop. Increment a counter each time a new image is displayed. Try this:
function rotateThumbs(otherImages, theImage) {
var i = 0;
var interval = setInterval(function() {
$('#'+theImage).attr('src', otherImages[i++]);
if (i >= otherImages.length) {
clearInterval(interval);
}
}, 1000);
}
I've implemented a fully-functional example here. This addresses some of the issues that #gilly3 notes, but uses closures instead of an incrementing counter to keep track of the current image:
$(function() {
$('img').hover(function() {
// declaring these variables here will preserve
// the references in the function called by setInterval
var $img = $(this),
imageList = $img.attr('class').split('#'),
intervalId;
// start the cycle
intervalId = window.setInterval(function() {
var next = imageList.pop();
if (next) {
$img.attr('src', next);
} else {
// stop the cycle
intervalId = window.clearInterval(intervalId);
}
}, 1000);
}, function() {});
});
As you can see, using a closure is much easier when you declare the function passed to setInterval inline, rather than as a separate, named function. You could still have a rotateThumbs function if you wanted, but you might need to do some more work to ensure that the variables were being passed properly.
Edit: I made an updated version that continues to cycle as long as the mouse is hovering.
I have adjusted the answer for Sam, taking pre-loading the image into account, so that you won't have a possible deplay at the first rotation.
function rotateThumbs(otherImages, theImage) {
if(!$('#'+theImage).data('setup')){
$('#'+theImage).data('setup', true); // do not double pre-loading images
var $body = $('body');
for(var j = 0; j < otherImages.length; j++){
$body.append($('<img/>').attr('src', otherImages[j])
.css('display', 'none'));
}
}
var i= 0;
setInterval(function(){
$('#'+theImage).attr('src', otherImages[i++]);
if(i >= otherImages.length){i = 0}
}, 1000);
}