skip to Main Content

I made this code so that when you click one of the nine images, you get another one (I made images with text on Photoshop). My code works fine but it is just really long. Does anyone know how to make it shorter?

Javascript:

	$(document).ready(function() { /*Altijd aanroepen per script*/


	  $(document)
	    .on('click', '#imgClickAndChange', function changeImage() {

	      if (document.getElementById("imgClickAndChange").src == "http://127.0.0.1:50150/img/thirdtwo.png") {
	        document.getElementById("imgClickAndChange").src = "http://127.0.0.1:50150/img/thirdtwohover.png";
	      } else {
	        document.getElementById("imgClickAndChange").src = "http://127.0.0.1:50150/img/thirdtwo.png";
	      }
	    })

	  $(document)
	    .on('click', '#imgClickAndChange2', function changeImage() {

	      if (document.getElementById("imgClickAndChange2").src == "http://127.0.0.1:50150/img/thirdone.png") {
	        document.getElementById("imgClickAndChange2").src = "http://127.0.0.1:50150/img/thirdonehover.png";
	      } else {
	        document.getElementById("imgClickAndChange2").src = "http://127.0.0.1:50150/img/thirdone.png";
	      }
	    })

	  $(document)
	    .on('click', '#imgClickAndChange3', function changeImage() {

	      if (document.getElementById("imgClickAndChange3").src == "http://127.0.0.1:50150/img/thirdthree.png") {
	        document.getElementById("imgClickAndChange3").src = "http://127.0.0.1:50150/img/thirdthreehover.png";
	      } else {
	        document.getElementById("imgClickAndChange3").src = "http://127.0.0.1:50150/img/thirdthree.png";
	      }
	    })

	  $(document)
	    .on('click', '#imgClickAndChange4', function changeImage() {

	      if (document.getElementById("imgClickAndChange4").src == "http://127.0.0.1:50150/img/thirdfour.png") {
	        document.getElementById("imgClickAndChange4").src = "http://127.0.0.1:50150/img/thirdfourhover.png";
	      } else {
	        document.getElementById("imgClickAndChange4").src = "http://127.0.0.1:50150/img/thirdfour.png";
	      }
	    })

	  $(document)
	    .on('click', '#imgClickAndChange5', function changeImage() {

	      if (document.getElementById("imgClickAndChange5").src == "http://127.0.0.1:50150/img/thirdfive.png") {
	        document.getElementById("imgClickAndChange5").src = "http://127.0.0.1:50150/img/thirdfivehover.png";
	      } else {
	        document.getElementById("imgClickAndChange5").src = "http://127.0.0.1:50150/img/thirdfive.png";
	      }
	    })
	  $(document)
	    .on('click', '#imgClickAndChange6', function changeImage() {

	      if (document.getElementById("imgClickAndChange6").src == "http://127.0.0.1:50150/img/thirdsix.png") {
	        document.getElementById("imgClickAndChange6").src = "http://127.0.0.1:50150/img/thirdsixhover.png";
	      } else {
	        document.getElementById("imgClickAndChange6").src = "http://127.0.0.1:50150/img/thirdsix.png";
	      }
	    })
	  $(document)
	    .on('click', '#imgClickAndChange7', function changeImage() {

	      if (document.getElementById("imgClickAndChange7").src == "http://127.0.0.1:50150/img/thirdseven.png") {
	        document.getElementById("imgClickAndChange7").src = "http://127.0.0.1:50150/img/thirdsevenhover.png";
	      } else {
	        document.getElementById("imgClickAndChange7").src = "http://127.0.0.1:50150/img/thirdseven.png";
	      }
	    })
	  $(document)
	    .on('click', '#imgClickAndChange8', function changeImage() {

	      if (document.getElementById("imgClickAndChange8").src == "http://127.0.0.1:50150/img/thirdeight.png") {
	        document.getElementById("imgClickAndChange8").src = "http://127.0.0.1:50150/img/thirdeighthover.png";
	      } else {
	        document.getElementById("imgClickAndChange8").src = "http://127.0.0.1:50150/img/thirdeight.png";
	      }
	    })
	  $(document)
	    .on('click', '#imgClickAndChange9', function changeImage() {

	      if (document.getElementById("imgClickAndChange9").src == "http://127.0.0.1:50150/img/thirdnine.png") {
	        document.getElementById("imgClickAndChange9").src = "http://127.0.0.1:50150/img/thirdninehover.png";
	      } else {
	        document.getElementById("imgClickAndChange9").src = "http://127.0.0.1:50150/img/thirdnine.png";
	      }
	    })



	});
CSS:
#pictures {
  background-color: rgb(35, 35, 35);
  color: rgb(204, 55, 77);
  text-align: center;
  padding-top: 2%;
  padding-bottom: 2%;
  width: 100%;
  min-height: 100vh;
  float: left;
  overflow: hidden;
  font-size: 30px;
}
.onethird {
  margin-left: 1%;
  margin-right: 1%;
  margin-top: 5%;
  width: 25%;
}
<div id="pictures">
  <img src="img/thirdtwo.png" class="onethird" id="imgClickAndChange" onclick="changeImage()"></img>
  <img src="img/thirdone.png" class="onethird" id="imgClickAndChange2" onclick="changeImage()"></img>
  <img src="img/thirdthree.png" class="onethird" id="imgClickAndChange3" onclick="changeImage()"></img>
  <img src="img/thirdfour.png" class="onethird" id="imgClickAndChange4" onclick="changeImage()"></img>
  <img src="img/thirdfive.png" class="onethird" id="imgClickAndChange5" onclick="changeImage()"></img>
  <img src="img/thirdsix.png" class="onethird" id="imgClickAndChange6" onclick="changeImage()"></img>
  <img src="img/thirdseven.png" class="onethird" id="imgClickAndChange7" onclick="changeImage()"></img>
  <img src="img/thirdeight.png" class="onethird" id="imgClickAndChange8" onclick="changeImage()"></img>
  <img src="img/thirdnine.png" class="onethird" id="imgClickAndChange9" onclick="changeImage()"></img>

</div>
</div>

5

Answers


  1. Remove onclick attributes, as you don’t need them (and it’s not really good practice to use them). click event handlers are set in yur JS code.

    This should do the job for your HTML example:

    $('.onethird').click(function(e){
        var old_src = $(this).attr('src');
        var new_src = old_src.indexOf('hover') > -1 ? old_src.replace('hover', '') : old_src.split(".")[0] + 'hover.png';
        $(this).attr('src', new_src);
    });
    
    Login or Signup to reply.
  2. I would recommend two things. First put both your urls on each of your elements.

    <img src="img/thirdtwo.png" class="onethird" id="imgClickAndChange1" data-src="img/thirdtwo.png" data-srchover="img/thirdtwohover.png"></img>
    

    Then when they all follow that pattern you could do something like:

    $(document).on('click', '.onethird', function() {
        var $this = $(this);
    
        if ($this.is('.hoverDisplayed')) {
            //is hover, so we need to revert it
            $this.attr('src', $this.data('src');
        } else {
            //is not hover, so make it hover
            $this.attr('src', $this.data('srchover');
        }
    
        //toggle the class to reflect what it should be next time
        $this.toggleClass('hoverDisplayed');
    });
    
    Login or Signup to reply.
  3. function hoverFile(filename){
        if (filename.indexOf('hover') != -1){
            // remove hover
            console.log('remove');
            var updatedFilename = filename.replace('hover','');
        }
        else {
            // add hover
            console.log('add');
            var extension = filename.substr(filename.lastIndexOf('.')+1);
            var originalFilename = filename.substr( 0, filename.indexOf( "." ) );
            var updatedFilename = originalFilename + 'hover.' + extension;
        }
        return updatedFilename;
    }
    
    $(document).ready(function() { /*Altijd aanroepen per script*/
        $('.onethird').click(function() {
            console.log('before: ' + this.src);
            this.src = hoverFile(this.src);
            console.log('after:' + this.src);
        });
    });
    <div id="pictures">
        <img src="img/thirdtwo.png" class="onethird"></img>
        <img src="img/thirdone.png" class="onethird"></img>
        <img src="img/thirdthree.png" class="onethird"></img>
        <img src="img/thirdfour.png" class="onethird"></img>
        <img src="img/thirdfive.png" class="onethird"></img>
        <img src="img/thirdsix.png" class="onethird"></img>
        <img src="img/thirdseven.png" class="onethird"></img>
        <img src="img/thirdeight.png" class="onethird"></img>
        <img src="img/thirdnine.png" class="onethird"></img>
    </div>
    Login or Signup to reply.
  4. Try this..

    $(document).on('click', '.onethird', function changeImage() {
      var imagePath = document.getElementsByClassName("onethird")[0].src;
    if (imagePath  == "http://127.0.0.1:50150/img/thirdtwo.png") {
           imagePath = "http://127.0.0.1:50150/img/thirdtwohover.png";
    }
    else if ( imagePath  == "http://127.0.0.1:50150/img/thirdtwo.png") {
           imagePath  = "http://127.0.0.1:50150/img/thirdtwohover.png";
    }
    .
    .
    .
    .
    
    else{
          imagePath  = "http://127.0.0.1:50150/img/thirdtwo.png";
    }
    
    });
    
    Login or Signup to reply.
  5. Unfortunarely I already started working on a solution for you before I saw others posted, oh well! Here is what I wrote up for you.

    I went with one general click event listener for a generic class you can apply to all your images you want to swap when clicked. When an image is clicked, it will swap images with names you defined using the data- attribute available on HTML elements. I am using the jQuery .attr() function because I do not know which jQuery version you’re using and .data() isn’t available for earlier versions of jQuery. Please let me know if this works out for you, or if I need to make adjustments. Code is posted below, cheers!

    JavaScript

    $(document).ready(function() {
      var totalImages = 10;
      var basePath = '/img/';
      var hoverClass = 'is-hover';
      var clickImageSelector = '.imgClickAndChange';
    
      function changeImage() {
          var $img          = $(this);
          var hoverImg  = $img.attr('data-hover-img');
          var staticImg = $img.attr('data-static-img');
    
          if ($img.hasClass(hoverClass)) {
              // Set Image SRC to staticImg if using hoverImg
              // (determined by existance of hoverClass)
              $img.attr('src', basePath + staticImg);
              $img.removeClass(hoverClass);
          }
          else {
              // Set Image SRC to hoverImg if using staticImg
              // (determined by existance of hoverClass)
              $img.attr('src', basePath + hoverImg);
              $img.addClass(hoverClass);
          }
      }
    
      $(document).on('click', clickImageSelector, changeImage);
    });
    

    HTML

    <div id="pictures">
      <img src="img/thirdone.png" class="imgClickAndChange onethird" data-static-img='thirdone.png' data-hover-img='thirdonehover.png' />
      <img src="img/thirdtwo.png" class="imgClickAndChange onethird" data-static-img='thirdtwo.png' data-hover-img='thirdtwohover.png' />
      <img src="img/thirdthree.png" class="imgClickAndChange onethird" data-static-img='thirdthree.png' data-hover-img='thirdthreehover.png' />
      <img src="img/thirdfour.png" class="imgClickAndChange onethird" data-static-img='thirdfour.png' data-hover-img='thirdfourhover.png' />
      ...
      <img src="img/thirdnine.png" class="imgClickAndChange onethird" data-static-img='thirdnine.png' data-hover-img='thirdninehover.png' />
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search