2hTu2 2hTu2 - 3 months ago 8
Javascript Question

Why does this button not rotate is visual studio?

If you run this code snippet you will see a button. If you click on it, it will rotate. I have the exact same code in Visual Studio (as you can see in the picture below). However, when i debug the code or press 'view in browser (Google Chrome)' it doesn't work at all.



$("#rotate").click(function () {
if ($(this).css("transform") == 'none') {
$(this).css("transform", "rotate(45deg)");
} else {
$(this).css("transform", "");
}
});

body {
}

#rotate {
width: 30px;
height: 30px;
}

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/css.css" />
<script src="scripts/jquery-2.1.1.js"></script>
<script src="scripts/JavaScript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button id="rotate"></button>
</body>
</html>





enter image description here

Answer

Did you wrap your button binding inside $(document).ready(function () { });? That is not clear from your example because it works fine if it is.

Or place your javascript code beneath the button without the &(document).ready function, that also works because if it is above the button the browser will try to bind a button that does not exits yet.

    <script>
        $(document).ready(function () {
            $("#rotate").click(function () {
                if ($(this).css("transform") == 'none') {
                    $(this).css("transform", "rotate(45deg)");
                } else {
                    $(this).css("transform", "");
                }
            });
        });
    </script>
    <style>
        #rotate {
            width: 100px;
            height: 30px;
        }
    </style>
    <button id="rotate" type="button">button</button>
Comments