Home > Software design >  To change the images by using onclick function but it is not working
To change the images by using onclick function but it is not working

Time:08-29

html code I have used the above html code

Javascript code The above is the javascript code and onclick function is not working

CodePudding user response:

You are accessing the small images by the id attribute, but they have no id attribute. The small-img is a class.

Your JS code should look something like this:

var MainImag=document.getElementById('MainImg');
var SmallImg=document.getElementsByClassName('small-img');

Also you should consider using jQuery approach instead of binding the click event on every single one image:

$('.small-img').on('click', function () {
    var src = $(this).attr('src');
    $('#MainImg').attr('src', src);
});
  • Related