Huckster
Huckster

Reputation: 37

Add class via JS

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..

Upvotes: 1

Views: 124

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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.

Upvotes: 3

Related Questions