0

So I've never coded before in JavaScript, I just tried using it today, because I thought it would be useful in my html website design. I added 2 JS files. The first file makes it so the link of my anchor element changes every 2 seconds. The other file makes it so the source of an image element changes every 2 seconds. When I remove the link changing file the image changes, but when I add the link changing file the image doesn't change anymore. There are no errors on the console.

Link changing file:

var links = ['https://www.youtube.com', 'https://stackoverflow.com', 'https://twitter.com'];


var indeks = 0;
const linkElement = document.querySelector('.link');


function changeLink() {
   linkElement.href = links[indeks];
   indeks > 1 ? indeks = 0 : indeks++;
}

window.onload = function () {
    setInterval(changeLink, 2000);
};

Image changing file:

var images = ['images/display/1.jpg', 'images/display/2.jpg', 'images/display/3.jpg'];


var index = 0;
const imgElement = document.querySelector('.photo');


function otherImage() {
   imgElement.src = images[index];
   index > 1 ? index = 0 : index++;
}

window.onload = function () {
    setInterval(otherImage, 2000);
};

The link does change every 2 seconds but the image doesn't. Both of these files are linked in the bottom of my html file. When I remove <script src="js/link.js"></script> from my html file the images DOES change for some reason.

I want to make it so the image changes every 2 seconds and the link changes every to seconds.

  • 1
    The problem might be with the two `window.onload`s. The last one will remove the previously assigned function. Try using `addEventListener` like `window.addEventListener("load", (event) => { setInterval(changeLink, 2000); });` in both files. – Ramesh Reddy Apr 02 '23 at 16:25

0 Answers0