0

I have a code like this,

<head runat="server">
    <title>Sidebar</title>
    <link href="css/style.css" rel="stylesheet" />
    <script src="scripts/jquery-1.11.1.min.js"></script>
    <script src="scripts/main.js"></script>
</head>
<body>
    <i class="open-icon" data-open="false"></i>
    <div class="contact-form-ch">
    </div>

    <div class="container">
        <div class="content-1"></div>
    </div>

    <script>
        $(".open-icon").on("click", function () {
            var statu = $(this).data("open");

            if (statu) {
                $(".contact-form-ch").animate({ "width": "700px" });
                $("body").animate({ "margin": "0" });
                $(this).removeAttr("data-open").attr("data-open", false);
            } else {
                $(".contact-form-ch").animate({ "width": "700px" });
                $("body").animate({ "margin": "0 -350px 0 350px" });
                $(this).removeAttr("data-open").attr("data-open", true);
            }

        });

    </script>
</body>

When I run the first this project. this code return false

var statu = $(this).data("open");

That's ok, because, data-open="false"

But when I click <i class="open-icon" data-open="false"></i> data-open will be replace with true So, would be <i class="open-icon" data-open="true"></i>

But var statu still and always return false. But It must be true on runtime. How can i solve this problem?

aynakolik
  • 89
  • 1
  • 1
  • 9

2 Answers2

4

You simply need to use .data()

 $(this).data("open", true/false); //Set value using data

instead of

 $(this).removeAttr("data-open").attr("data-open", true/false)

A Good Read for you: jQuery Data vs Attr?

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
2

Try this:

$(".open-icon").on("click", function () {
            var statu = $(this).data("open");

            if (statu) {
                $(".contact-form-ch").animate({ "width": "700px" });
                $("body").animate({ "margin": "0" });
                $(this).data("open", false);
            } else {
                $(".contact-form-ch").animate({ "width": "700px" });
                $("body").animate({ "margin": "0 -350px 0 350px" });
                $(this).data("open", true);
            }

        });

JSFiddle

Vikram
  • 675
  • 6
  • 25