-1

I have several same html blocks with svg. I wanna add toggle class by click. This code doesn't work. Console.log is called but class isn't added.

    $( document ).ready(function() {
        init_svg();
        $('.seat').click(function(){
            if($(this).hasClass('preorder')){
                $(this).removeClass('preorder');
                console.log(1);
            }
            else{
                console.log(2);
                $(this).addClass("preorder");
            }           
        });
    });
    <div class="order" style="top: 260px; right: 370px;">
        <svg version="1.1" id="table-4" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"
        style="transform: rotate(-15deg);"
        width="100px" height="100px">
            <circle class="table" cx="60" cy="60" r="30"></circle>
            <circle class="seat" cx="28.888" cy="28.884" r="6"></circle>
            <circle class="seat" cx="17.5" cy="48.608" r="6"></circle>
            <circle class="seat" cx="17.5" cy="71.384" r="6"></circle>
            <circle class="seat" cx="28.888" cy="91.108" r="6"></circle>
            <circle class="seat" cx="48.612" cy="102.497" r="6"></circle>
            <circle class="seat" cx="71.388" cy="102.497" r="6"></circle>
            <circle class="seat" cx="91.113" cy="91.109" r="6"></circle>
            <circle class="seat" cx="102.502" cy="71.385" r="6"></circle>
            <circle class="seat" cx="102.502" cy="48.609" r="6"></circle>
            <circle class="seat" cx="91.114" cy="28.883" r="6"></circle>
        </svg>
      </div>

What is wrong?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
V-K
  • 1,297
  • 10
  • 28
  • I've removed the *snippet* feature from your question since the code was clearly not intended to actually run (the snippet feature is not a general purpose code sharing tool). – Álvaro González Feb 13 '17 at 12:52
  • You must be using **old version** of jQuery :/ https://github.com/jquery/jquery/issues/2199 – vsync Feb 13 '17 at 12:58

1 Answers1

0

JQuery is unable to add a class to an SVG.

.attr() works with SVG you have to do something like this

// Instead of .addClass("newclass")
$("#item").attr("class", "oldclass newclass");
// Instead of .removeClass("newclass")
$("#item").attr("class", "oldclass");

very good explanation is available on this thread of SO:

jQuery SVG, why can't I addClass?

Community
  • 1
  • 1
danish farhaj
  • 1,316
  • 10
  • 20