1

I have some JS that switches grid img on click. It also delays the href to the second click. Therefore allowing the switched to img to show.

What I wish to do is on the first click, also add a class so that another JS code (a typewriter effect) will run.

This is the JS that switches the img:

$(document).ready(function(){
  $('#s1').click(function(e) {
    if (!$(this).is('[src*="switch"]')) {
      $('#s1').attr('src', 'img/switch/switch-1.jpg');
      $('#s2').attr('src', 'img/box-2.jpg');
      $('#s3').attr('src', 'img/box-3.jpg');
      $('#s4').attr('src', 'img/box-4.jpg');
      $('#s5').attr('src', 'img/box-5.jpg');
      $('#s6').attr('src', 'img/box-6.jpg');
      $('#s7').attr('src', 'img/box-7.jpg');
      $('#s8').attr('src', 'img/box-8.jpg');
      $('#s9').attr('src', 'img/box-9.jpg');
      $('#s10').attr('src', 'img/box-10.jpg');

      return false;
    }
  });
});

Thanks for reading..

2
  • Ooooof, looks like there is a lot of unnecessary redundancy/bloat in your code Commented Mar 23, 2017 at 14:49
  • Use addClass to add a new class to an element. See the documentation of jQuery for more information: api.jquery.com/addclass Commented Mar 23, 2017 at 14:49

1 Answer 1

3

What I wish to do is on the first click, also add a class

If you want just to add class why not using .addClass() :

$('#s1').click(function(e) {
    $(this).addClass('new_class');
});

NOTE : If the posted code is your real case, you could avoid the duplicated code using loop :

var start_index = 2;
var end_index = 10;

for(var i = start_index; i<= end_index; i++){
    $('#s' + i).attr('src', 'img/box-' + i + '.jpg');
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Zakaria,Yes loads of help, thanks for the loop also I will look into streamlining the code a bit. Many thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.