0

I've written a Simple function in Javascript which calls a jQuery function the problem is Why do I need to click button to get the toggle effect

html

<input id="toggle" type="button" value="Toggle" onclick="toggle()" />

javascript

<script type="text/javascript">
function toggle()
{
    new_toggle();
}
</script>

jQuery

$(function new_toggle2(){
        $('#toggle').click(function(){

    $('#p1').toggle(); // Simple <p> and <h1> tags
            $('#h').toggle();   
        });
    new_toggle = new_toggle2;
});
2
  • Because you have specified onclick="toggle()" ??? Commented Oct 11, 2012 at 14:17
  • What do you want to call the toggle function, instead of clicking the button? Commented Oct 11, 2012 at 14:19

4 Answers 4

1

I believe this will be sufficient for click event.

HTML:

<input id="toggle" type="button" value="Toggle" />

JS:

$(function(){
        $('#toggle').click(function(){

            $('#p1').toggle(); // Simple <p> and <h1> tags
            $('#h').toggle();   
        });
});
Sign up to request clarification or add additional context in comments.

Comments

1

You have this code with you:

<input id="toggle" type="button" value="Toggle" onclick="toggle()" />

The toggle() is the function, which should be initiated. That function is bound to the <input> tag with the help of onclick= attribute. The onclick event is used to execute a JavaScript when an element is clicked.

If you want to trigger that function on page load, then a small change is required. The toggle() function should be called when the document loads.

$(document).ready(function () {
    toggle();
}

Comments

1

I think you're a little bit confused about it...

Remove:

onclick="toggle()"

and:

<script type="text/javascript">
function toggle()
{
    new_toggle();
}
</script>

And write just this:

$(function(){
    $('#toggle').click(function(){

        $('#p1').toggle();
        $('#h').toggle();   
    });
});

1 Comment

Thank You !! Very much man .... A slight change in jQuery's Code n I got the result ..Cheers !!
0

Reading a lot into your question! - If you want your toggle function to fire on page load, rather than when you click the button change your function to:

<script type="text/javascript">
    $(document).ready(function () {
            new_toggle2();
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.