Search code examples
javascriptjqueryfunctionevent-handlingclick

Removing an onclick function


I'm currently playing around with creating a new image slider for a project, but had a question. The task is to have an image displayed on page that will open the full size onclick. However, I'd like to make it so the function goes away and the image returns to the original state onclick again.

Here's my code:

<html>
<head>
    <title>Fullscreen</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>

<body>
    <img src="//path" onClick="full()" id="image" />
    <script type="text/javascript">
        function full() {
            $(function () {
                $('#image').on('click', function () {
                    $(this).width(1000);
                });
            }); 
        }
    </script>
</body>   
</html>

The image opens in a larger state which is good, but how would I implement a second onclick function to take away the first?

Thanks for the help!


Solution

  • To take an event previously assigned use

    $('#image').off('click')
    

    To scale back the image, use

    var size = 0;
    function full() {
        $(function () {
            $('#image').on('click', function () {
                if (size === 0) {
                    size = $(this).width();
                    $(this).width(1000);
                } else {
                    $(this).width(size);
                    size = 0;                     
                }
            });
        }); 
    }