I am trying to get the background image of a div to change at an interval. I created an Array with the images, and every few seconds the function should check the value of "x" against the array length. If X is less, x will increase by one and the background image will change to the next image in the array, otherwise it will set x=0 and restart the process.
The div and initial image shows up how I want, but nothing happens.
I know there are probably better ways to do this, but I am very new to Javascript and want to learn why this code doesn't work. Thanks in advance for the help!!
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ImageChanger</title>
<style type="text/css">
#imagediv {
float:left;
border-style:ridge;
border-width:8px;
border-color:Green;
border-radius:15px;
width:1250px;
height:450px;
background-image:url(images/landscape1.jpg)
}
</style>
<script type="text/javascript">
function displayNextImage() {
var x;
If (x<imageArray.length) {
x=x+1;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
else {
x=0;
document.getElementById("imagediv").style.backgroundImage=images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var imageArray=new Array();
images[0] = "images/landscape1.jpg";
images[1] = "images/landscape2.jpg";
images[2] = "images/landscape3.jpg";
images[3] = "images/landscape4.jpg";
</script>
</head>
<body>
<div id="imagediv">
</div>
</body>
</html>
If (x<imageArray.length) {..
should be
if (x<imageArray.length) {
Javascript is case-sensitive.
Also you have some missing braces like you are not closing
function displayNextImage() { ....
Use your browser console to debug. These syntax errors will be shown there.
As far as syntax issues go:
As #Zee stated, If should be lowercase (if)
Also, as #Zee and some others stated, you are not closing function displayNextImage() { with a closing brace }.
You are improperly defining the background-image property in your function, whereas you defined it correctly in the block of CSS. You must wrap the image name with url().
You are never calling your timeout function, startTimer.
You create a new array imageArray but then use an undeclared array images
Related
So I have this HTML code to just show pictures on a browser, every click transitions to the next picture. My question is how can i make Slide13 automatically go to Slide14 after 4 seconds then go back to clicking to transition between pictures? Thanks!!
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Slide1.PNG</title>
</head>
<body onclick="step()">
<img id="image_id" src="" style="width:100%;height:100%">
</body>
<script type="text/javascript">
var images=[
"Slide1.PNG",
"Slide2.PNG",
"Slide3.PNG",
"Slide4.PNG",
"Slide5.PNG",
"Slide6.PNG",
"Slide7.PNG",
"Slide8.PNG",
"Slide9.PNG",
"Slide10.PNG",
"Slide11.PNG",
"Slide12.PNG",
"Slide13.GIF",
"Slide14.PNG",
"Slide15.GIF",
"Slide16.PNG",
"Slide17.PNG",
"Slide18.PNG",
"Slide19.PNG",
"Slide20.GIF",
"Slide21.PNG",
"Slide22.PNG",
"Slide23.PNG",
"Slide24.PNG",
"Slide25.PNG",
"Slide26.PNG",
"Slide27.PNG",
"Slide28.PNG",
"Slide29.PNG",
"Slide30.PNG",
"Slide31.PNG",
"Slide32.PNG",
"Slide33.PNG",
"Slide34.PNG"
];
var index=0;
var imageObjects=images.map(function(img){var imgTag=new Image();imgTag.src=img});
function step(){
document.getElementById('image_id').src=images[(index++)%images.length];
}
step();
</script>
</html>
Add this to your step:
var image = document.getElementById("image_id").src;
if (image=="Slide13.GIF") {
setTimeout(function(){
document.getElementById('image_id').click();}, 4000);
}
It will check on every step the source value of image, when it hits Slide13.GIF it will emulate the click on it after 4 seconds and go to next one.
See below demo, on 3ed image it will click it after 2 seconds.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Slide1.PNG</title>
</head>
<body onclick="step()">
<img id="image_id" src="" style="width:100%;height:100%">
</body>
<script type="text/javascript">
var images=[
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.zYTlTH6b_YYEeNCvZsznjgHaD5%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.ZJA-xTrw2bHQaUXA6buoGwHaDt%26pid%3DApi&f=1",
"https://media2.giphy.com/media/YmbxC8Bkj9bZ4yu4Le/source.gif",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.qz01j4K29bmGqCy1hIwGswHaFf%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia1.tenor.com%2Fimages%2Fea490bc9d89afaf7d2431a0374aef65c%2Ftenor.gif%3Fitemid%3D15761601&f=1&nofb=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.wae3QtVQ_QQvkeaQ3alxzgHaEY%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.xd0rh27OUOrMUw8_ACG0HwHaDt%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.adQHsWv9A37aVRLNDLLlkwHaEK%26pid%3DApi&f=1",
"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.3nRZ72gyQTUakC-ZbhQ_MQHaHa%26pid%3DApi&f=1"
];
var index=0;
var imageObjects=images.map(function(img){var imgTag=new Image();imgTag.src=img});
function step(){
document.getElementById('image_id').src=images[(index++)%images.length];
var image = document.getElementById("image_id").src;
console.log(image);
if (image=="https://media2.giphy.com/media/YmbxC8Bkj9bZ4yu4Le/source.gif" || image=="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia1.tenor.com%2Fimages%2Fea490bc9d89afaf7d2431a0374aef65c%2Ftenor.gif%3Fitemid%3D15761601&f=1&nofb=1") {
setTimeout(function(){ document.getElementById('image_id').click(); }, 3000);
}
}
step();
</script>
</html>
EDIT:
It does work with gifs, i Just added two of them, on step 3 and 5. Also if you need more conditions in your if statement separate them with || Like so:
if (image=="https://media2.giphy.com/media/YmbxC8Bkj9bZ4yu4Le/source.gif" ||
image=="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia1.tenor.com%2Fimages%2Fea490bc9d89afaf7d2431a0374aef65c%2Ftenor.gif%3Fitemid%3D15761601&f=1&nofb=1") {
As seen in edited demo now it will do a click on two gifs, number 3 and 5.
You can add console.log(image); below image variable to see correct image source and use that in condition.
If you have problems with finding paths you can use this as your conditions:
if (image.indexOf("Slide13.GIF") >= 0 || image.indexOf(" other pic ") >= 0")
This will check if image variable of source value contains your wanted image title.
Hii this is my second question i will try to explain. This is a code which close the window after 3 seconds i want new window english.html should appear. thanks
<html>
<head>
<script>
function loaded()
{
window.setTimeout(CloseMe, 3000);
}
function CloseMe()
{
window.close();
}
</script>
</head>
<body onLoad="loaded()">
Hello!
</body>
You can't open a new window in response to anything other than a user interaction. "Three seconds after the page has loaded" is not a user interaction so will be blocked by the standard popup blocking rules that all modern browsers are required to implement by the HTML specification.
Try redirecting the user instead, or better yet, don't: Skip the three second page entirely. If something is worth showing to the user, then it is worth showing to the user until they click a link. That way you know they weren't giving their attention to another tab while your content waltzed by unnoticed.
Below is a simple example of how to achieve what you want:
//<![CDATA[
// external.js
var doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){ // load start
// I threw in a few goodies to study - it will help you later
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
T = function(tag){ // returns an Array of Elements by tag name
return doc.getElementsByTagName(tag);
}
// notice that `window` is implicit, so you don't actually need to use it to access its properties
setTimeout(function(){ // unexecuted functions and Anonymous functions behave the same
location = 'https://www.w3.org'; // it's really this easy to set the `window.location.href`
}, 3000);
});// load end
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div>Just a very simple example</div>
</div>
</body>
</html>
Note: You should practice using external sources so they can be cached. Just make sure you change the filename and path to any source you later change.
I have a HTML file with several JS scripts :
<!DOCTYPE html> <html>
<head>
<title>Application</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="initMap.js"></script>
<script src="CSVParsing.js"></script>
<script src="nbCinemas.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MYKEY&libraries=geometry&callback=initMap"></script>
</head>
<body>
<div id="map" style="width:1000px; height:800px; margin-left:auto; margin-right:auto;"></div>
</body>
My problem is that in my nbCinemas.js file, I am using a global variable that is supposed to have been initialised in CSVParsing.js... but it is not. The thing is, I think that my CSVParsing.js file is loading last. Here is the file:
var arrayData;
d3.csv("cinemas-a-paris.csv", function(data) {
data.forEach(function(d) {
d.lat = +d.lat;
d.lng = +d.lng;
});
arrayData = data;
print();
});
function print() {
console.log("done");
}
In the console, "done" is the last thing written, even though there are other console.logs in my nbCinemas.js file.
Can you help me? Why is my CSVParsing.js file loading last? How can I force it into loading before nbCinemas.js?
Thank you!
Tom.
First, probably
d3.csv("cinemas-a-paris.csv", function(data) {
data.forEach(function(d) {
d.lat = +d.lat;
d.lng = +d.lng;
});
arrayData = data;
print();
});
Is something that is happening in async, so it is send to the event loop, and the "done"message is just show up without that the past function had been finished.
After that, the next file is loaded and initialized and occurs the problem that you have.
One way to deal with this is, verifying that your global variable exists and, if it does, loading dynamicly your next js file like this:
// checking out the variable...
if (typeof variable !== 'undefined') {
// ...the variable is defined, so
var script = document.createElement('script');
script.src = 'http(s)://yourWebSiteURl.com/..js/nbCinemas.js';
}
This way you might ensure that this one last file is loading just after your global variable already exists
I have a JavaScript statement on the bottom of my page that I want to trigger ONLY if a certain HTML comment is available
<!-- mytriggercomment -->
In the above example, if the mytriggercomment is detected within the current page, only then should the JavaScript statement trigger. What is the preferred way of doing this?
May not work for older browsers, but this way is a logical DOM approach:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function () {
var treeWalker = document.createTreeWalker(
document,
NodeFilter.SHOW_COMMENT,
{acceptNode: function(node) {
if (node.nodeValue.trim() === 'mytriggercomment') {
return NodeFilter.FILTER_ACCEPT;
}
}}
);
var nodeList = [];
while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
alert(nodeList)
};
</script></head>
<body>
</body>
</html>
<!-- mytriggercomment -->
If you know it will always be at the bottom, you may be able to target it like:
window.onload = function () {
alert(document.documentElement.nextSibling &&
document.documentElement.nextSibling.nodeValue.trim() === 'mytriggercomment')
};
i want to know length of a tags
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length)
}
}
</script>
</head>
<body>
first
second
third
<input type="submit" onclick="clickme()"/>
</body>
Since value is not a standard property of a link, you will probably need to use .getAttribute("value"):
var x = document.getElementsByTagName('a');
for (var i=0; i<x.length;i++){
alert(x[i].getAttribute("value"));
}
In this example, x[i] is a anchor DOM Element object. It doesn't have a value property normally. However, if you want to use the property, you can access it via:
x[i].getAttribute('value');
Personally, I would use HTML5 data attributes and define the anchor like:
one
Then access the value via:
x[i].getAttribute('data-value');
If a HTML5 doctype is used, this will be valid.
I'm confused, you've changed your original question code sample from:
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].value) //<- "value" not a valid property on the anchor tag
}
}
</script>
to
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length) //<- "length" not a valid property on the anchor tag
}
}
</script>
If you're just trying to determine what the ordered number of that anchor tag itself is, you could just use "i" (and again - var it!):
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for( var i=0;i<x.length;i++) {
alert(i);
}
}
</script>
Or am I missing something that you're asking?
jfriend00 got that right.
I thought I'd also point out though that you might want to declare "i" either ahead of, or inline with your for. Otherwise you're using a global "i" that could have unexpected consequences elsewhere.