We help IT Professionals succeed at work.

jQuery .toggle() function question

elepil
elepil asked
on
778 Views
Last Modified: 2014-12-28
A book I'm reading says "The toggle() function enables you to execute one of several functions, whenever a HTML element is clicked."

But when I run my example, something weird happens. The target HTML element somehow disappears!?? Can anyone tell me what's wrong?

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery Test Page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
	$("document").ready(function(e) {
            $("#myDiv1").toggle(function() {
                console.log("This is the first function");
            }, function() {
                console.log("This is the second function");
            });
	});
</script>
<body>
    <div id="myDiv1" class="contentDiv" style="background: #ccc;">
        This is Div1<br/>
        <ul>
            <li>John Doe</li>
            <li>Jane Doe</li>
        </ul>
    </div>
<div id="myDiv2" class="contentDiv">Div 2</div>
<div id="myDiv3" class="contentDiv">Div 3</div>

</body>
</html>

Open in new window


Also, the book further says that "You can pass as many functions to toggle() as you like (not just 2)." But when I enter a third function, I get an error from Netbeans that says "Uncaught TypeError: undefined is not a function".

Can anyone enlighten me on this?
Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
If you click the div you make it disappear
Normally your click event isn't on the element you want to toggle e.g. in your case you might toggle the UL

Author

Commented:
I got the impression that the functions I provide will just execute alternatingly. But you're saying the div itself is supposed to disappear?? It even says I can provide more than two functions.

Sorry, but your answer did not help me at all.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
No, if you hide the div how are you supposed to be able to click it again - which is what your code is doing?

You don't hide the element that has the click event attached to it
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
You might do something like this

http://jsfiddle.net/n8cxL0fr/

            $("#myDiv1").click(function() {
		$("ul",this).toggle(function(){
                console.log("This is the first function");
            }, function() {
                console.log("This is the second function");
            });
            });

Open in new window

Author

Commented:
Now you're totally confusing me. The book does NOT say anything about defining a click event. In fact, it's example is as simple as this:

<script type =" text/ javascript" >
    $(document).ready(function() {
        $('#theDiv').toggle(function() {
            alert("Div clicked once"); 
        }, function() { 
            alert("Div clicked twice");
        }); 
    }); 
</script >

<div id="theDiv">The div ...</div>

Open in new window


But even its example confuses me because when I run it, the second function runs right away, even though it describes a reaction only to a click. So now I'm totally confused on how this function is supposed to behave.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
What is it you are trying to do?
Your current code makes no sense, you are saying hide the div on page load and that is it - there is not click event like in my example, you can't have multiple conditions on it because you are just hiding it.

See my example above for an example of the toggle conditions.

To hide something at page load with no interaction you would just do
	    $("#myDiv1").toggle(function () {
	        console.log("This is the first function");
	    });

Open in new window

Author

Commented:
Gary, unless you're telling me the book is totally wrong, you're not making sense. Please reread my original post because you're responding as if you haven't. First, the book does NOT say I should define a click handler, which you did. Second, I still do not have an explanation why the second function (per the example from the book) is executing right away.

If you just tried out the small code snippets I've provided, you will see what I mean and realize how your introduction of a click handler throws a monkey wrench into my question.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Your original code just hides the div at page load - there is no click event.
Once it's fired it will never be called again.

So what is the point of the function?

unless you're telling me the book is totally wrong
Wouldn't be the first time a book has it wrong.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
And as for why the second function fires - I'm not sure, but an educated guess, because a toggle would normally be attached to another event, so I guess since there is no event (like a click) with which to toggle between the two functions it just fires the last function

Author

Commented:
I don't even understand why it hides the div upon running, especially when the book mentions nothing about hiding. I gave you the exact wording of the book, and it is a very short section. Also, when I run the book's example, it does NOT hide anything, it just executes the second function.

The last sample you gave me came up with syntax errors, and I couldn't figure out why. I've even counted the brackets, and I couldn't get rid of it.

Grabbing my code, why don't you modify it and show me your point? You code it the way you want, as long as it's demonstrating the toggle() function, how's that?
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Well that is what the code is doing - hiding the div at page load

I already gave you a proper example of the toggle() function here along with a working fiddle
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
This might be a version issue, just checking what has changed with toggle()

Author

Commented:
Gary, I just looked at your toggle() sample through jsfiddle. I don't think we're talking about the same toggle().

My book describes toggle() as toggling in EXECUTION of the functions I provide it when the element is clicked. It talks nothing about hiding. And your example does not even execute any of the two functions. It's seeming to me now that your toggle() is different from the toggle() I'm asking about.
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Boy, now THAT is an excellent answer! So we were both dealing with two different toggle() functions after all. Thanks for your help!
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Thought I was going mad for a second :o)

Author

Commented:
Gary, how come your jsfiddle example never executes the first function?

Author

Commented:
I was going crazy, too. It's like you and I were talking in to different directions (which we were).

But I did learn the toggle() you were demonstrating, and it's nifty. But I am puzzled why it never executes the first function. Because I can find this toggle() pretty handy, I can do something when the element collapses or expands, but not when it never executes the first function. Can you tell me why?
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
I wasn't really examing the code but just adding to it.
To do the similar now you would do something like

http://jsfiddle.net/n8cxL0fr/2/

clickety_click = 0
$("#myDiv1").click(function () {
    if (clickety_click==0) {
        clickety_click = 1
    } else {
        clickety_click = 0
    }
})

Open in new window

Author

Commented:
Huh?? That last sample you gave doesn't even use toggle().
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
It toggles on the click
On the first click the first condition is met
On the second click the second condition is met
On the third click the first condition is met
....
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
http://jsfiddle.net/n8cxL0fr/3/

clickety_click = 0
$("#myDiv1").click(function () {
    if (clickety_click==0) {
        console.log("This is the first function");
        clickety_click = 1
    } else {
        console.log("This is the second function");
        clickety_click = 0
    }
})

Open in new window

Author

Commented:
Gary, your sample does not even use the toggle() function anymore. Nothing is happening. Did you even test your code?
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
Nothing is happening except logging to the console
You add in whatever you want to happen on each click and alternate click

Author

Commented:
But you used toggle(func1, func2), providing it with two functions. What was the point? And also, only the second function kept executing, so clearly those two function arguments were having an effect.

Can you please rewrite your jsfiddle using the toggle() function, demonstrating the two functions executing alternatingly and still collapsing the div tag?
CERTIFIED EXPERT
Expert of the Year 2014
Top Expert 2014

Commented:
I'm confused - so now you want to hide it?

http://jsfiddle.net/n8cxL0fr/4/

clickety_click = 0
$("#myDiv1").click(function () {
    $("ul", this).toggle(function () {
        if (clickety_click == 0) {
            console.log("This is the first function");
            clickety_click = 1
        } else {
            console.log("This is the second function");
            clickety_click = 0
        }
    })
})

Open in new window

Author

Commented:
Gary, I reposted this question at https://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28587652.html. This way you can get credit.

Author

Commented:
Gary, go to https://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28587652.html.

Remember, my original toggle() question was not about hiding. But now that you've proven that to be deprecated and removed, your sample intrigued me, which was a toggle() that hides. So yes, my new question is now about the toggle() example you provided.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.