Solved

jQuery .toggle() function question

Posted on 2014-12-28
28
311 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?
0
Comment
Question by:elepil
  • 15
  • 13
28 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 40521046
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
0
 

Author Comment

by:elepil
ID: 40521051
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.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521061
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
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521064
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

0
 

Author Comment

by:elepil
ID: 40521076
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.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521090
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

0
 

Author Comment

by:elepil
ID: 40521107
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.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521110
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.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521115
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
0
 

Author Comment

by:elepil
ID: 40521116
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?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521118
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
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521121
This might be a version issue, just checking what has changed with toggle()
0
 

Author Comment

by:elepil
ID: 40521131
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.
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 40521133
The toggle you are trying to do has been removed since 1.9

http://jquery.com/upgrade-guide/1.9/#toggle-function-function-removed

The book must be referencing 1.8.x or lower which is over 2 years ago

So you could always change the library you are using.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Closing Comment

by:elepil
ID: 40521135
Boy, now THAT is an excellent answer! So we were both dealing with two different toggle() functions after all. Thanks for your help!
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521140
Thought I was going mad for a second :o)
0
 

Author Comment

by:elepil
ID: 40521142
Gary, how come your jsfiddle example never executes the first function?
0
 

Author Comment

by:elepil
ID: 40521148
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?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521152
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

0
 

Author Comment

by:elepil
ID: 40521157
Huh?? That last sample you gave doesn't even use toggle().
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521160
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
....
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521162
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

0
 

Author Comment

by:elepil
ID: 40521165
Gary, your sample does not even use the toggle() function anymore. Nothing is happening. Did you even test your code?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521166
Nothing is happening except logging to the console
You add in whatever you want to happen on each click and alternate click
0
 

Author Comment

by:elepil
ID: 40521170
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?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40521172
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

0
 

Author Comment

by:elepil
ID: 40521173
Gary, I reposted this question at http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28587652.html. This way you can get credit.
0
 

Author Comment

by:elepil
ID: 40521179
Gary, go to http://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.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now