Jump to content

Combining codes


TheCarlaG

Recommended Posts

Hello!

I am trying to create a filterable portfolio with this https://www.w3schools.com/howto/howto_js_portfolio_filter.asp but I want to be able to click on each photo and have it expand like in this https://www.w3schools.com/howto/howto_css_modal_images.asp.

The crazy part is that I am successful in doing this with only one photo on the page, but can't get the others to do it. I've tried everything I can think of and can't get it to work.

The page I'm working on is here: http://www.ayutla-construction.com/gallery.php

 

Can anyone please guide me? I'd really appreciate it. It's been a thorn in my side for a while now.

Link to comment
Share on other sites

Elements id attributes have to be unique. When you call getElementById() it gives you just one element, all the other ones are ignored.

To affect multiple elements you need to use a function which can return a list of nodes, like querySelectorAll() or getElementsByClassName(), then you can loop through them and add event listeners to them.

If you change your <img> tags from id="myImg" to class="myImg" then this code will listen for clicks on all of the images:

var images = document.getElementsByClassName("myImg");
for(let i = 0; i < images.length; i++) {
  images[i].addEventListener("click", e => {
    document.getElementById("myModal").style.display = "block";
    document.getElementById("img01").src = this.src;
    document.getElementById("caption").innerHTML = this.alt;
  });
}

 

Link to comment
Share on other sites

The block of code I provided should work as long as the HTML for the modal box and the images is there and the Javascript code is further down in the document than the elements are.

If it's not working, check the browser developer tools to see if any errors appear.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...