Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 402
  • Last Modified:

jQuery .toggle() function question

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
elepil
Asked:
elepil
  • 15
  • 13
1 Solution
 
GaryCommented:
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
 
elepilAuthor 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.
0
 
GaryCommented:
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
GaryCommented:
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
 
elepilAuthor 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.
0
 
GaryCommented:
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
 
elepilAuthor 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.
0
 
GaryCommented:
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
 
GaryCommented:
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
 
elepilAuthor 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?
0
 
GaryCommented:
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
 
GaryCommented:
This might be a version issue, just checking what has changed with toggle()
0
 
elepilAuthor 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.
0
 
GaryCommented:
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
 
elepilAuthor Commented:
Boy, now THAT is an excellent answer! So we were both dealing with two different toggle() functions after all. Thanks for your help!
0
 
GaryCommented:
Thought I was going mad for a second :o)
0
 
elepilAuthor Commented:
Gary, how come your jsfiddle example never executes the first function?
0
 
elepilAuthor 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?
0
 
GaryCommented:
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
 
elepilAuthor Commented:
Huh?? That last sample you gave doesn't even use toggle().
0
 
GaryCommented:
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
 
GaryCommented:
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
 
elepilAuthor Commented:
Gary, your sample does not even use the toggle() function anymore. Nothing is happening. Did you even test your code?
0
 
GaryCommented:
Nothing is happening except logging to the console
You add in whatever you want to happen on each click and alternate click
0
 
elepilAuthor 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?
0
 
GaryCommented:
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
 
elepilAuthor Commented:
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
 
elepilAuthor Commented:
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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 15
  • 13
Tackle projects and never again get stuck behind a technical roadblock.
Join Now