Hamed mayahian
Hamed mayahian

Reputation: 2323

add "attribute" or Class to variable

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?

Upvotes: 0

Views: 216

Answers (4)

Praveen
Praveen

Reputation: 56501

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.

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20408

use add class and remove class

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

It also removes other elaments current class

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

use addClass() to add a class attribute

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

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128791

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');

Upvotes: 3

Related Questions