Javascript not working in wordpress
-
Forgive my stupidity on this I have never worked with Javascript before and I am struggling with it. I have a very basic understanding of php, mysql, html, and css.
I am trying to create a very basic image gallery where someone can select an image and I can insert the product_id associated with that image into a ?add-to-cart url.
So far I have written the code to get the products, their images, everything I need. I then foreach and create a simple photo gallery with the product_id stored in the alt= of the img.
Now the hard part how to allow someone to select the img (without having to reload the page). I went to W3schools found a javascript photo gallery and using their “try it editor” I paired it down a lot and made some small changes. The code works in thier editor, but when I put it in wordpress the gallery shows up, but it wont let me select the images.
here is the code:
<div class="colorway" style="float:left; padding:5px;"> <div class="img"> <img src="color_1.jpg" alt="product_id" width="100"> <div class="desc">Color 1 </div> </div> </div> <div class="colorway" style="float:left;padding:5px;"> <div class="img"> <img src="color_2.jpg" alt="product_id" width="100" > <div class="desc">Color 2</div> </div> </div> <div class="colorway" style="float:left;padding:5px;"> <div class="img"> <img src="color_3.jpg" alt="product_id" width="100"> <div class="desc">Color 3</div> </div> </div> <div class="colorway" style="float:left;padding:5px;"> <div class="img"> <img src="color_4.jpg" alt="product_id" width="100"> <div class="desc">Color 4</div> </div> </div> <div style="clear:both;"></div> <!-- The Modal --> <div id="myModal" class="modal"> <span class="close"></span> <img class="modal-content" id="img01"> <div id="caption"></div> </div> <script> // Get the modal var modal = document.getElementById('myModal'); // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // Get all images and insert the clicked image inside the modal // Get the content of the image description and insert it inside the modal image caption var images = document.getElementsByTagName('img'); var modalImg = document.getElementById("img01"); var captionText = document.getElementById("caption"); var i; for (i = 0; i < images.length; i++) { images[i].onclick = function(){ modal.style.display = "block"; modalImg.src = this.src; modalImg.alt = this.alt; modalImg.width = 300; captionText.innerHTML = '<a href ="http://www.mydomain.com/cart/?add-to-cart=' + modalImg.alt +'">ADD TO CART</a>'; } } </script>I would really appreciate any suggestions. Thank you! I am also open to other ways of making this work.
The topic ‘Javascript not working in wordpress’ is closed to new replies.