0

I am working on slideshow. At the end I want to add current class to my variable for next checking.

But that's not work, I also tried attr but not working.

this is my code:

    $(function () {
        $('.large_image').children('img').addClass('current');
        $('.product-item').click(function () {
            if ($('.large_image > img').hasClass('current')) {
                var $img = $(this).find('img').attr('data-img');
                var $slider = '<img class="dis-none" style="position:absulote;z-index:999" src=' + $img + ' />';
                $($slider).appendTo('.large_image').stop(true, true).delay(400).fadeIn(
                   function () {
                       $('.current').fadeOut(function () {
                           $(this).remove();

                       });
                   });
                $($slider).attr('class', 'current');
                $($slider).addClass('current');
            }
        })
    });

Any help on how to resolve this issue?

timrau
  • 22,578
  • 4
  • 51
  • 64
Hamed mayahian
  • 2,465
  • 6
  • 27
  • 49

4 Answers4

3

Firstly, your variable name is $slider, not slider. You'll need to add a $ before slider: $($slider). After fixing this, you can simply use jQuery's addClass() method:

$($slider).addClass('current');

jQuery also has a removeClass() method to remove the class, so before setting the new slide to "current", you may want to call:

$('.current').removeClass('current');
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
1

use addClass() to add a class attribute

$(slider).addClass("current");
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Below is the actual mistake in your code.

$($slider).attr("class='current'"); //WRONG
$($slider).attr('class','current'); //RIGHT WAY

or simply using addClass() method

$($slider).addClass('current');

Check this Benefits of using attr() over addClass in jquery

addClass() has several benefits over manipulating the class with attr('class'):

  1. It's semantically clearer.
  2. It works with multiple classes.
  3. It's apparently a lot faster.
Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
1

use add class and remove class

$(slider).addClass('current').siblings().removeClass('current');

It also removes other elaments current class

Sridhar R
  • 20,190
  • 6
  • 38
  • 35