My self made slider doesn't work - javascript

I have a problem with my self made image slider, i get the error: Uncaught TypeError: Cannot set property 'src' of null
Edit: I have called all images like this: img1, img2, img3 etc with extension .jpg
this is my javascript code:
// JavaScript Document
var imagecount = 1;
var total = 3;
window.setInterval(function slideA(x)
{
var Image = document.getElementById('img');
imagecount = imagecount + x;
if(imagecount > total) { imagecount = 1; }
if(imagecount < 1) { imagecount = total; }
Image.src = "images_slider/img" + imagecount + ".jpeg";
}, 5000);
function init()
{
slideA();
}
window.onload = init;
<div id="LandingImage">
<img src="../images/landingimage.png" alt="LandingImage" width="100%" height="100%" />
</div>
Can someone help me with this?
Thanks!
Kevin.

Your html element does not have an id of img, you appear to be trying to select the tag name.
I also suggest not using Image as the variable name, since Image is an object name in JavaScript.
<img src="../images/landingimage.png" alt="LandingImage" width="100%" height="100%" id="img" /> <!-- id at the end, was missing -->

It appears that you are trying to iterate through a list of images by changing the source of an image. If so, refer to the following JS fiddle for an example:
https://jsfiddle.net/hqq1k2Lk/3/
I made a few changes, so let's go through it together.
// JavaScript Document
var imagecount = 1;
var total = 3;
function slideA()
{
//slideA starts the interval
window.setInterval(function(){
var myImage = document.getElementById('LandingImage');
imagecount++;
if(imagecount > total) { imagecount = 1; }
if(imagecount < 1) { imagecount = total; }
myImage.src = "images_slider/img" + imagecount + ".jpeg";
}, 5000);
}
function init()
{
slideA();
}
window.onload = init();
First, I moved your function call slideA outside the interval. Thus calling slideA(); will start the interval.
Next, I moved your ID LandingImage to the img element itself, so we can get the image from the DOM using document.getElementById('LandingImage');
Since you need to keep track of what image you're on, I elected to use imagecount as your counter. You can increment a number by 1 by using ++ such as imagecount++;
As others have pointed out Image is a protected object name in Javascript, so I renamed your variable to myImage
Lastly, in order to start the whole process, I added a function call to your window onload event. Whenever you want to call a function, remember to use ()
window.onload = init();

As another poster mentioned, do not use Image as your variable name.
To access the src attribute of the element, you use element.setAttribute('src', 'insert src here') not element.src.

Related

Is there a way to switch images src back to original after on.click src change event?

I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.

Loop images on hover - setInterval issue

My code is running well...
but there is one thing I can't solve:
when I mouseover the image the loop starts well, but on subsequent mouseovers it starts changing faster and faster...
var Image = new Array("//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP");
var Image_Number=0;
var Image_Length= Image.length;
function change_image(num){
Image_Number = Image_Number + num;
if(Image_Number > Image_Length)
Image_Number = 0;
if(Image_Number < Image_Length)
document.slideshow.src = Image[Image_Number];
return false;
Image_Number = Image_Length;
}
function auto () {
setInterval("change_image(1)", 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseover="auto()" />
On every mouseover you're reassigning a brand-new-intervalâ„¢ resulting in multiple functions running at the same time.
name on IMG tag is an obsolete HTML5 attribute - See also img tag # W3.org
"change_image(1)" ...strings inside setInterval or setTimeout tigger eval. Which is bad. The real function name should be used instead: setInterval(functionName, ms)
You're not managing well the argument num
You cannot have code after a return statement
Use the mouseenter event (instead of mouseover)
and many more errors....
Here's a remake:
var images = [
"//placehold.it/400x180/?text=Welcome",
"//placehold.it/400x180/?text=To",
"//placehold.it/400x180/?text=My",
"//placehold.it/400x180/?text=Web+page",
"//placehold.it/400x180/?text=INPHP"
];
var c = 0; // c as Counter ya?
var tot = images.length;
var angryCat = false;
// Preload! Make sure all images are in tha house
for(var i=0; i<tot; i++) {
var im = new Image();
im.src= images[i];
}
function changeImage() {
document.slideshow.src = images[++c%tot];
}
function auto() {
if(angryCat) return; // No more mouse enter
angryCat = true;
setInterval(changeImage, 1000);
}
<img src="//placehold.it/400x180/?text=Welcome" name="slideshow" onmouseenter="auto()" />
The increment and loop is achieved using ++c % tot
The angryCat boolean flag helps to know it the auto() already started (mouse was there!), in that case it will return; (exit) the function preventing the creation of additional overlapping intervals on subsequent mouseenter (which was your main issue).
Additionally, I'd suggest to keep your JS away from HTML, so instead of the JS attribute event
onmouseenter="auto()"
assign an ID to your image id="myimage" and use JS:
document.getElementById("myimage").addEventListener("mouseenter", auto, false);

Javascript Pic Slideshow Failing?

FOr some reason my code is not executing properly. i am trying to program a slideshow with javascript. Im using a for loop to pull and populate the src files from a created array and change the pic every 3 seconds. THe page loads and the first pic is present but when the interval occurs the first pic dissapears and nothing falls in its place. What am I doing wrong?
<img name="mainSlide" id="mainSlide" src="images/mainPagePhotos/facebook-20131027-180258.png" alt="">
var mainSlidePics = ("facebook-20131027-180258.png","IMG_9694116683469.jpg","IMG_28452769990897.jpg");
window.onload = setInterval("mainSlide();", 3000);
function mainSlide() {
for(i=0; i<mainSlidePics.length; i++ ) {
document.images.mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
}
}
Have you tried getting the Id first?
var mainSlide = document.getElementById("mainSlide");
mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
also a forloop is a loop that finishes its loops even in one call.
try
var i = 0;
window.onload = setInterval("mainSlide(i);", 3000);
mainSlide(int j){
mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[i];
setInterval("mainSlide(j++);", 3000);
}
First you have to correctly declare the array.
Then you have to move the counter variable outside the function triggered by setInterval.
Then pass the reference of the function to setInterval.
<img name="mainSlide" id="mainSlide" src="images/mainPagePhotos/facebook-20131027-180258.png" alt="">
<script type="text/javascript">
var mainSlidePics = ["facebook-20131027-180258.png","IMG_9694116683469.jpg","IMG_28452769990897.jpg"];
var position = 0;
function changePic() {
position = (position+1) % mainSlidePics.length;
document.images.mainSlide.src = "images/mainPagePhotos/" + mainSlidePics[position];
}
window.onload = function() {
setInterval(changePic, 3000);
};
</script>

change image using javascript based on function result

I've been searching and trying to figure this out for hours but i seem to be missing something. Basically i'm trying to make it so if i click a link/button it executes a script to increase or decrease the number by a specified amount in a function. (in this example its by 1)
The image files that im trying to display are supposed to change depending on the final result. but the image never changes.
any suggestions are greatly appreciated
<script type="text/javascript">
var p1hps = 20;
var p1hpimage
function p1p1Click() {
p1hps = (p1hps +1);
function p1health(){
};
}
function p1health() {
p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1health();
}
</script>
<body>
<img src="images/p1p1.png" width="165" height="87" alt="">
<img src="images/p120.png" id="p1hp" width="324" height="252" alt="">
</body>
You need to invoke the p1health function inside p1p1Click, instead you were declaring another function with the name p1health inside p1p1Click.
Also the images src property, you need to assign the value of the variable p1hpimage instead of recursively calling the p1health method
var p1hps = 20;
function p1p1Click() {
p1hps++;
p1health();
}
function p1health() {
var p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1hpimage ;
}
Demo: Fiddle -- inspect the source with dev tools to see the src getting updated
Try this :
var _myPicArray =new Array("pic1.png","pic2.png","pic3.png");
function p1health(n) {
document.getElementById('p1hp').src = myPicArray[n] ;
}

Getting images to change in a for loop in javascript

So far I created an array with 11 images, initialized the counter, created a function, created a for loop but here is where I get lost. I looked at examples and tutorial on the internet and I can see the code is seeming simple but I'm not getting something basic here. I don't actually understand how to call the index for the images. Any suggestions. Here is the code.
<script type="text/javascript">
var hammer=new Array("jackhammer0.gif",
"jackhammer1.gif",
"jackhammer2.gif",
"jackhammer3.gif",
"jackhammer4.gif",
"jackhammer5.gif",
"jackhammer6.gif",
"jackhammer7.gif",
"jackhammer8.gif",
"jackhammer9.gif",
"jackhammer10.gif")
var curHammer=0;
var numImg = 11;
function getHammer() {
for (i = 0; i < hammer.length; i++)
{
if (curHammer < hammer.length - 1) {
curHammer = curHammer +1;
hammer[i] = new Image();
hammer[i].src="poses/jackhammer" +(i+1) + ".gif";
var nextHammer = curHammer + 1;
nextHammer=0;
{
}
}
}
}
setTimeout("getHammer()", 5000);
</script>
</head>
<body onload = "getHammer()";>
<img id="jack" name="jack" src = "poses/jackhammer0.gif" width= "100" height ="113" alt = "Man and Jackhammer" /><br/>
<button id="jack" name="jack" onclick="getHammer()">Press button</button>
Following on what Paul, said, here's an example of what should work:
var hammer=["jackhammer0.gif","jackhammer1.gif","jackhammer2.gif","jackhammer3.gif",
"jackhammer4.gif","jackhammer5.gif","jackhammer6.gif","jackhammer7.gif",
"jackhammer8.gif","jackhammer9.gif","jackhammer10.gif"];
var curHammer=0;
function getHammer() {
if (curHammer < hammer.length) {
document.getElementById("jack").src= "poses/" + hammer[curHammer];
curHammer = curHammer + 1;
}
}
setTimeout("getHammer()", 5000);
The big missing element is that you need to call getElementById("jack") to get a reference to the DOM Image so that you can change it's source. If you're using jQuery or most other JS frameworks, just type $("#jack") to accomplish the same.
I don't understand the need for the for loop at all, just increment the index value [curHammer] each time you click, and reset if it passes your max index length (in this case 11).
Pseudo-Code:
currentHammer = -1
hammers = [ "a1.jpg", "a2.jpg", "a3.jpg"]
getHammer()
{
currentHammer = currentHammer + 1;
if(currentHammer > 2)
currentHammer = 0;
image.src = hammers[currentHammer];
}
a) are you just trying to show an animated gif? If so, why not use Adobe's Fireworks and merge all those gifs into a single gif?
b) you know that the way you have it the display is going to go crazy overwriting the gif in a circle right?
c) you might want to put a delay (or not). If so, make the load new gif a separate function and set a timeout to it (or an interval).
Also, you are being redundant. How about just changing the src for the image being displayed?:
var jackHammer = new Array();
for (var i=0;i<11;i++) { //pre-loading the images
jackHammer[i] = new image();
jackHammer[i].src = '/poses/jackHammer'+i.toString()+'.gif';
} //remember that "poses" without the "/" will only work if that folder is under the current called page.
for (var i=0;i<11;i++) { //updating the image on
document.getElementById('jhPoses').src = jackHammer[i].src;
}
on the document itself,
< img id='jhPoses' src='1-pixel-transparent.gif' width='x' height='y' alt='poses' border='0' />

Categories

Resources