<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<img name="img" src="http://4.bp.blogspot.com/-Jdj5JKTA1xQ/T-BzvrQDZhI/AAAAAAAABhs/bX0TUEFb3Ck/s1600/windows-help1.png" width="90%" height="100%">
<script>
setInterval(function () {
var images = document.getElementsByTagName('img'); // get all img DOM objects
for (var i = 0; i < images.length; i++) {
images[i].src = images[i].src.replace(/\btime=[^&]*/, 'time=' + new Date().getTime());
}
}, 1000);
</script>
</body>
</html>
In Chrome I can see my picture refresh every second, but in IE version 9 it does not work. It does not refresh after displaying one time. How can I solve this problem, or is there any other way to do it?
The code, as is, should work. Also in IE 9.
Try something like this to verify that the scr attribute actually get changed:
Sample fiddle
JSFiddle does not work well in IE 8 – which I tested on, but this should give you a viewable sample for IE:
Sample fiddle
HTML:
<img src="http://jsfiddle.net/img/initializing.png?time=123" />
<img src="http://jsfiddle.net/img/initializing.png?time=123" />
<br/>
Img0.src: <input type="text" /><br/>
Img1.src: <input type="text" /><br />
Counter : <input type="text" />
CSS:
input {
width : 500px;
}
Javascript:
var img = document.getElementsByTagName('img');
var inp = document.getElementsByTagName('input');
var cnt = 0;
setInterval(function () {
inp[2].value = ++cnt;
for (var i = 0; i < img.length; i++) {
img[i].src = img[i].src
.replace(/\btime=[^&]*/, 'time=' + new Date().getTime());
inp[i].value = img[i].src;
}
}, 1000);
Related
I am stuck on my homework project. I am supposed to create a JavaScript program that shows an animated puppy running. I must use caching to start the animation as soon as the images finish loading and 1 of the following: getElementsByName(), getElementById(), or getElementsByTagName(). Here's what I have so far but when I run it in Firefox all I see is a flashing box that says "image of a puppy"
<!DOCTYPE HTML>
<html>
<head>
<title>Running Puppy</title>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<script type="text/javascript">
/* <![CDATA[ */
var puppy = new Array(6);
var curPuppy = 0
for (var imagesLoaded=0; imagesLoaded < 6;
++imagesLoaded) {
puppy[imagesLoaded] = new Image();
puppy[imagesLoaded].src
= "images/puppy" + imagesLoaded + ".gif";
}
function run(){
if (curPuppy == 5)
curPuppy = 0;
else
++curPuppy;
document.getElementById("puppyImage").src = puppy[curPuppy].src;
}
/*]]> */
</script>
</head>
<body onload="setInterval('run()', 150)">
<img src="images/puppy0.gif" id="puppyImage" width="263" height="175" alt="Image of a puppy." />
<script type="text/javascript">
/* <![CDATA[ */
document.write("<h1 id='mainHeading'></h1>");
document.getElementById("mainHeading").innerHTML = document.getElementsByTagName("title")[0].innerHTML;
/*]]> */
</script>
</body>
</html>
So I am doing something very basic that can be done with CSS but I want to do it with jQuery to get familiar with the library.
I am trying to create a rollover image gallery. Where when you put the mouse over the image it will be swapped with a slightly edited version of it.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<style>
</style>
</head>
<body>
<div id="gallery">
<img src="images/one_s.jpg" />
<img src="images/two_s.jpg" />
<img src="images/three_s.jpg" />
<img src="images/four_s.jpg" />
<img src="images/five_s.jpg" />
<img src="images/six_s.jpg" />
</div>
<script>
$(document).ready(function(){
var alternate = ['images/one_s_edited.jpg',
'images/two_s_edited.jpg',
'images/three_s_edited.jpg',
'images/four_s_edited.jpg',
'images/five_s_edited.jpg',
'images/six_s_edited.jpg'];
var $selection = $("#gallery img");
for(var i = 0; i < alternate.length; i++)
{
var imgObject = new Image();
var downloadedImg = imgObject.src = alternate[i];
console.log(downloadedImg);
var originalSrc = $selection.eq(i).attr("src");
console.log(originalSrc + "\n");
$selection.eq(i).hover(
function(){
$(this).attr("src", downloadedImg);
},
function(){
$(this).attr("src", originalSrc);
}
);//End hover
}//End loop
});//End ready
</script>
</body>
</html>
Here is a link to the final result: link
As you can see it rolls over but not as planned. It ends up with the last rollover-image and doesn't change back to the original nor does it show the appropriate rollover image that corresponds with it.
Any simple suggestions without using regular expressions?
The problem is the wrong usage of a closure variable in a loop.
But the solution can be simplified to
$(document).ready(function () {
var $selection = $("#gallery img");
$selection.hover(function () {
this.src = this.src.replace('.jpg', '_edited.jpg')
}, function () {
this.src = this.src.replace('_edited.jpg', '.jpg')
})
}); //End ready
For image upload in a cakephp project I used java-script.I added this js file in app\View\Layouts default.ctp
js code
document.querySelector('input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
if (files[i].type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
event.target.value = '';
I have checked there are no problem.
now in add.ctp file I adder
<input type="file" multiple />
In output I am seeing the file type field.Now when I clicked on this field and upload a image then mojila bug given me a error.That is
document.querySelector(...) is null error
I have no idea about this error.In here why saying queryselector is null?
document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.
I would suggest you call all JS script bottom of the page.
To make sure that your DOM is ready you could add this to your JS file.
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.querySelector('input[type=file]')
.addEventListener('change', function(event){
...
}
});
This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.
Also take a look at this other Google rule.
file.js
const heading1 = document.querySelector(".heading1");
console.log(heading1);
Solution 1
Use defer (best & recommended way):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./file.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
</body>
</html>
Solution 2
Place your JavaScript in bottom before closing body tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
<script src="./file.js"></script>
</body>
</html>
I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag
There is now another "better" way to address this issue.
put your scripts in the head tag and add the defer attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="main.js" defer></script>
</head>
<body>
yoyoyo
</body>
</html>
you can read more about it here and here
TLDR (may be inaccurate and misleading so read the sources above!):
the defer attribute tells the browser to load the file but hold off its execution until the dom is ready, which is close to the behavior you implicitly get when you put the script tag at the bottom of the body tag, the difference being that in the old way you have to wait for the whole body tag to be parsed until you start downloading the script tag.
I ran into this issue where I was trying to do (slimmed down for simplicity):
<script type="text/javascript">
var svg = document.querySelector('svg');
console.log(svg);
</script>
on an element in the <body>:
<svg id="svg" viewBox="0 0 120 120" width="500px" height="500px"></svg>
Once I added jQuery and moved my lines inside of a $(document).ready(), it was fine:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var svg = document.querySelector('svg');
console.log(svg);
});
</script>
Here's a quick fix. I was trying to effect some changes in my HTML page using DOM and was getting this error. The problem was I linked my Javascript file inside the head tag of the HTML page, when I changed that and linked it at the body just before the closing body tag, it worked!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Soft dog</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="landing.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Cormorant+SC:wght#300&family=Edu+VIC+WA+NT+Beginner&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h2 id="newBrand">Welcome to SOFTDOG</h2>
<p><em>property of soft 6</em></p>
<a id="ceo" href="home.html"><img src="softdogmerch1.jpg" alt="check network"></a>
<p id="enterstatement">Please<a href="home.html">
<P><span>ENTER HERE</span></P>
</a><span>to feed your eyes and fill your wardrobe</span>
</p>
<label for="emailinput">email:</label>
<input id="emailinput" type="email" name="useremail" placeholder="user#email.com" required>
<label for="passwordinput">password:</label>
<input id="passwordinput" type="password" name="userpassword" placeholder="" required>
<input id="clickme" type="submit" name="login" value="log in">
<input id="clickme" type="submit" name="signup" value="sign up">
</div>
<script src="landing.js"></script>
</body>
</html>
I have a problem with javascript.
I need to add onclick listener for all img tags in my page, so click on an image should call imageClicked and pass element to function. but this code all time pass img src="../images/3.jpg" to function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample Page</title>
</head>
<body onload="start()">
<script type="text/javascript">
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
var image=images[i];
image.addEventListener('click', function(){
imageClicked(image);
});
}
}
function imageClicked(image){
alert(image.src)
}
</script>
<div id="main">
<div id="center">
<button>نمایش اسلایدی</button>
</div>
<div id="gallery">
<div id="img1" class="image">
<img src="../images/1.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
<div id="img2" class="image">
<img src="../images/2.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
<div id="img" class="image">
<img src="../images/3.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
</div>
</div>
That is because of the scope. Everytime you loop the image value is set again. And so it will always pass the last image in the loop.
You can do 2 thing. Use the this like below. Or create an anonymouse function.
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', function(){
imageClicked(this);
});
}
}
// Or even better
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', imageClicked);
}
}
function imageClicked(){
alert(this.src); // this refers to the image
}
Anonymouse function:
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
(function(image){
image.addEventListener('click', function(){
imageClicked(image); // Use the element clicked object (this)
});
})(images[i]);
}
}
What you want is something like this:
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', function(){
imageClicked(this);
});
}
}
function imageClicked(image){
alert(image.src)
}
In the code you wrote, you copied the image element and then assigned an eventListener to the copy of the object. Because this copy was over-written multiple times, imageClicked was referred to by the only one that wasn't over-written, the last image. The this is to refer to the actual image element in the callback function.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone suggest good javascript code to implement slideshow such that all the elements of slideshow are declared in or an array.I want it using purely javascript without using jQuery
This may be useful to you. Copy and replace images.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>image slide show</title>
<style type="text/css">
body {
background:#FFC;
}
input[type="button"] {
background:#939907;
color:#fff;
border:1px solid #434603;
-moz-border-radius:5px;
-webkit-border-radius:5px;
-ms-border-radius:5px;
font-weight:bold;
cursor:pointer;
height:25px;
}
img {
width:525px;
height:200px;
border:2px solid #CF3;
-moz-border-radius:15px;
-webkit-border-radius:15px;
-ms-border-radius:15px;
}
</style>
<script type="text/javascript">
var images=new Array();
var i=0, t, f=false;
images[0] ="images/heli1.jpg";
images[1] ="images/heli2.JPG";
images[2] ="images/heli3.JPG";
images[3] ="images/heli4.JPG";
images[4] ="images/heli5.JPG";
images[5] ="images/heli6.JPG";
images[6] ="images/heli7.JPG";
images[7] ="images/heli2.JPG";
images[8] ="images/heli9.JPG";
images[9] ="images/heli1.jpg";
images[10] ="images/heli2.JPG";
images[11] ="images/heli3.JPG";
images[12] ="images/heli4.JPG";
images[13] ="images/heli5.JPG";
images[14] ="images/heli6.JPG";
function start(){
if(i>=images.length){
i=0;
document.getElementById('img').src=images[i];
i++;
}
else{
document.getElementById('img').src=images[i];
i++;
}
t=setTimeout("start()", 1000);
}
function play(){
if(f==false){
f=true;
start();
}
}
function Stop(){
clearTimeout(t);
f=false;
}
function next(){
if(i>=images.length){
i=0;
document.getElementById('img').src=images[i];
i++;
}
else{
document.getElementById('img').src=images[i];
i++;
}
}
function previous(){
if(i>=images.lenght){
i=images.length;
document.getElementById('img').src=images[i];
i--;
}
else if(i<=0){
i=images.length;
document.getElementById('img').src=images[i-1];
i--;
}
else if(i>images.length){
document.getElementById('img').src=images[images.length-i];
}
else if(i<=images.length || i>0){
document.getElementById('img').src=images[i-1];
i--;
}
}
</script>
</head>
<body>
<table width="50%" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><input type="button" value="Previous" onclick="previous()" /></td>
<td align="center"><img src="images/heli6.JPG" alt="" id="img" /></td>
<td><input type="button" value="Next" onclick="next()" /></td>
</tr>
<tr>
<td colspan="3" align="center" height="50"><input type="button" value="Play" onclick="play()" />
<input type="button" value="Stop" onclick="Stop()" /></td>
</tr>
</table>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script language="javascript">
loaded_img = 0;
no_of_img = 12;
img_name = new Array();
img_name.length = no_of_img - 1;
for ( var count = 0; count < no_of_img; count++)
{
var file_num = count + 1;
var filename = ("img" + file_num + ".jpg");
img_name[count] = filename;
}
var whichlink=0
function slideit(){
if (!document.images)
return
document.images.myimage.src=img_name[loaded_img].src
whichlink=loaded_img
if (loaded_img<img_name.length-1)
loaded_img++
else
loaded_img=0
setTimeout("slideit()",1000)
}
slideit()
function changeImage(direction)
{
loaded_img=loaded_img+direction;
if (loaded_img < 0)
loaded_img = no_of_img - 1;
if (loaded_img == no_of_img)
loaded_img = 0;
document.myimage.src = img_name[loaded_img];
}
</script>
<script language="javascript">
//slideshowimages()=new Array()
//slideshowimages("img1.jpg")
var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.myimage.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",1000)
}
slideit()
</script>
<form>
<img src="left-disabled.gif" width="27" height="22" border="0">
<img src="img1.jpg" name="myimage">
<img src="right-enabled.gif" width="27" height="22" border="0">
</form>
</body>
</html>
This question is old, but here is a more comprehensive example with pure JavaScript. It assumes that index.html and slideshow.js are on the same level. It begins with an automatically playing slideshow (that can be paused and resumed), and it also has previous and next buttons. If you only want one of those sets of functionality, it should be fairly straightforward to remove the other.
The HTML is very barebones and can be altered as desired for the most part as long as you mind the ids. I haven't provided any styling, so that's all you.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>slideshow</title>
</head>
<body>
<section>
<div>
<img id="image">
</div>
<div>
<button type="button" id="playBtn">Play</button>
<button type="button" id="pauseBtn">Pause</button>
</div>
<div>
<button type="button" id="prevBtn">Prev</button>
<button type="button" id="nextBtn">Next</button>
</div>
</section>
<script src="slideshow.js"></script>
</body>
</html>
If you want to support IE8 and/or below, you'll need to ditch the DOMContentLoaded listener. Essentially, you could just extract the IIFE and then replace its final line return beginSlideshow with beginSlideshow(). I hope that makes sense, and I hope you find this helpful. Good luck.
// slideshow.js
document.addEventListener(
// IE 9 and up. See http://caniuse.com/#feat=domcontentloaded
'DOMContentLoaded'
, (function STRICT() {
'use strict';
// Avoid 'new' and stick to array literals where possible.
var images =
[ 'img/30.gif'
, 'img/31.gif'
, 'img/32.gif'
, 'img/33.gif'
, 'img/34.gif'
]
, img = document.getElementById('image')
, playBtn = document.getElementById('playBtn')
, pauseBtn = document.getElementById('pauseBtn')
, prevBtn = document.getElementById('prevBtn')
, nextBtn = document.getElementById('nextBtn')
, index = 0
, indexOfLastImage = images.length - 1
, play
, playInterval
, pause
, goToPrevious
, goToNext
, beginSlideShow
play = function() {
playInterval = setInterval(
function() {
if (index === indexOfLastImage) { index = 0 }
img.src = images[++index]
}
, 3000
)
}
pause = function() {
clearInterval(playInterval)
playInterval = null
}
goToPrevious = function() {
// if the slideshow was running
if (playInterval) { pause() }
// if we're at the beginning of the array
if (index === 0) {
index = indexOfLastImage + 1
}
img.src = images[--index]
}
goToNext = function() {
// if the slideshow was running
if (playInterval) { pause() }
// if we're at the beginning of the array
if (index === indexOfLastImage) {
index = -1
}
img.src = images[++index]
}
beginSlideShow = function() {
// add listeners
playBtn.addEventListener('click', play)
pauseBtn.addEventListener('click', pause)
prevBtn.addEventListener('click', goToPrevious)
nextBtn.addEventListener('click', goToNext)
// set initial image for display prior to first interval
img.src = images[index]
// kick off auto play
play()
}
// This is what's attached to and will fire on the DOMContentLoaded event
return beginSlideShow
}())
)