Link to home
Start Free TrialLog in
Avatar of elepil
elepil

asked on

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?
Avatar of Gary
Gary
Flag of Ireland image

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
Avatar of elepil
elepil

ASKER

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.
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
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

Avatar of elepil

ASKER

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.
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

Avatar of elepil

ASKER

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.
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.
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
Avatar of elepil

ASKER

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?
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
This might be a version issue, just checking what has changed with toggle()
Avatar of elepil

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of elepil

ASKER

Boy, now THAT is an excellent answer! So we were both dealing with two different toggle() functions after all. Thanks for your help!
Thought I was going mad for a second :o)
Avatar of elepil

ASKER

Gary, how come your jsfiddle example never executes the first function?
Avatar of elepil

ASKER

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?
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

Avatar of elepil

ASKER

Huh?? That last sample you gave doesn't even use toggle().
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
....
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

Avatar of elepil

ASKER

Gary, your sample does not even use the toggle() function anymore. Nothing is happening. Did you even test your code?
Nothing is happening except logging to the console
You add in whatever you want to happen on each click and alternate click
Avatar of elepil

ASKER

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?
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

Avatar of elepil

ASKER

Gary, go to https://www.experts-exchange.com/questions/28587652/jQuery-toggle-not-executing-functions-properly.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.