Use jQuery's animate function to toggle a different div when clicking on one

Having trouble with a jQuery function that keeps triggering the second function every time I click. How can I fix this issue?

I designed a navbar with 3 links, each linked to a different .contentDiv with unique IDs. Whenever a link is clicked, a toggle function occurs: hiding all other .contentDiv elements except for the one linked to the clicked link, accompanied by a sliding animation to the left.

Sample HTML:

.navbar
ul
    li
        a.about(href='#') About
            span
            span
    li
        a#portfolio(href='#') HOME
            span
            span
    li
        a(href='#') Contact
            span
            span
.contentDiv#portfolioContent
                    .title About
                    .content
                        .fse
                            p Lorem ipsum dolor sit amet, consectetur adipiscing elit. 

CSS:

    .contentDiv {
    transform: skew(45deg);
    width: 100%;
    height: 100%;
    position: relative;
    top: 5%;
    left: 300%;
    overflow: hidden;
}

.title {
    position: absolute;
    top: 30%;
    left: 30%;
    font-size: 500%;
    font-family: Raleway;
    font-weight: 800;
    color: #EAEBED;
}

.content {
    width: 100%;
    height: 50%;
    top: 43%;
    left: 3%;
    font-size: 130%;
    font-family: Raleway;
    color: #EAEBED;
    position: absolute;
    overflow:scroll;
    padding-bottom: 7%;
}

JQuery:

$('.about').click(function () {
    $("#aboutContent").toggle(
        function() {
            $("#aboutContent").animate({left: "115%"}, { //coming out of hiding
                duration: 2000
            });
        }, function() {
            $("#aboutContent").animate({left: "300%"}, { //back into hiding
                duration: 2000
            });
        }
    );
});

Answer №1

You have the ability to create a custom function named clickToggle that allows you to toggle between different functions when clicked:

For more information, visit: jQuery click / toggle between two functions

(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

$('.about').clickToggle(function() {
  alert("First handler for .toggle() called.");
   $("#aboutContent").toggle("Slow");
}, function() {
  alert("Second handler for .toggle() called.");
   $("#aboutContent").toggle("Slow");
});
#aboutContent {
  height: 200px;
  width: 200px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button class="about">
  CLICK
</button>

<div id="aboutContent">
  123123123
</div>

Answer №2

let counter = 1;
$('.about').click(function() {
  $("#aboutContent").toggle(function() {
    counter++;
    if (counter % 2 == 0) alert("1")
    else alert("2");
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
give this a try:
<button class="about">
  click
</button>

<div id="aboutContent">
  code..
</div>

Answer №3

In the latest version of jQuery, the toggle() function has been deprecated in v1.8 and completely removed in 1.9. Instead of toggling between two specified functions, it now alternates between show() and hide() only. You can read more about this change here.

If you need to create a custom toggle functionality, you can refer to another answer or visit this Stack Overflow post for alternative solutions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The select2 plugin seems to be having trouble recognizing the Li click functionality

I have a select menu that is using the select2 plugin. I am trying to add a class to the <select> element when a menu option is clicked, but it doesn't seem to be working as expected even after testing with an alert. https://jsfiddle.net/ysm4qh ...

What makes text-decoration a crucial element of the foreground design?

<span>Educating children on unlocking their creative and intellectual potential through the world of Computer Science.</span> Here is the HTML code provided above along with the corresponding CSS: span { text-decoration: underline; color: red ...

Grammarly is seamlessly inserting padding into my body element

After setting up my website on GitHub, I ran into an issue where the Grammarly Chrome extension was automatically adding a padding-top attribute to the body tag. <body data-new-gr-c-s-check-loaded="14.1028.0" data-gr-ext-installed="" ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

Learn how to send multiple checkbox values using jQuery and AJAX requests

When trying to extract the value from multiple checkboxes, I utilize this particular code snippet: <form class="myform" method="post" action=""> <input type="checkbox" class="checkbox" value="11" /><br> <input type="ch ...

Creating a WordPress Infographic: How to Design a "Wide" Graphic

I have a question for those who are experienced with infographics. I'm in the process of getting an infographic designed for my blog and I've noticed that some websites have a feature that allows the infographic to expand to full width when you c ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

Chosen option in jQuery dropdown menu

I am currently working on a dropdown menu that changes the window.location.href on selection. However, I am wondering how I can keep the selected value highlighted when the page reloads? <div class="iPhoneNav"> <select class="iPhoneDropdown ...

How can one ensure in Watin that the form is processed by the server before proceeding?

Currently, I am utilizing JavaScript to submit a form to my server within the view in order to initiate a server-side job. The completion of this job is detected by a JavaScript callback function being invoked. Although the specifics of the JavaScript comm ...

List that dynamically changes in HTML email template

I'm currently working on an email template using HTML, and I've run into a roadblock while trying to create a list based on Java code data. The challenge is that the length of the list varies each time. Here's what I tried: <span st ...

When submitting an Asp net mvc Form, some fields may not be posted as expected

I'm facing an issue with my ASP.NET MVC application form. Some fields that should be posted are missing, and I can't figure out why. <form id="FormRegistroUsuario" action="/Account/AdminSecurityUserAccountAdd"> <fieldset> ...

Selenium is unable to locate an element using Jquery

sel.add_script( sel.get_location(), "jquery.js") #I am getting u'fd6c42bcc770ca9decc4f358df3688290a4257ad' idOfResultWithSomeImage=sel.get_eval("window.jQuery('#result').find('img').filter('[alt=SeleImage]') ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...

Tips on finding a JavaScript file using Google search

After releasing my jQuery plugin, I've noticed an increase in downloads. However, I'm curious to know where exactly it is being utilized. One idea I had was to search for the .js or .css file, potentially even looking at folder names. Is there a ...

Creating an array of form input names using JavaScript within the HTML input tag

I have a two part question that I'm hoping someone can help me with. There was a similar question asked recently that included information about this particular type of array in PHP, but unfortunately, I can't seem to locate it at the moment. 1. ...

Guide on implementing "Displaying 1 of N Records" using the dataTables.js framework

let userTable = $("#user_table").DataTable({ 'sDom': '<"row-drop"<"col-sm-12 row"lr>><"row"t><"row-pager"<"col-sm-12 col-md-5"i><"col-sm-12&qu ...

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

Icon Searchbar Feature in Ionic 2

I am currently working with Ionic2 and have integrated the ion-searchbar component into my project: https://i.sstatic.net/CqmF4.png Question Would it be possible to customize the search icon? The default icon is a magnifying glass, but I would like to r ...

A platform for creating ER and flow diagrams specifically tailored for web applications, utilizing open source software

Our team is currently working on creating a web application that enables users to create diagrams, such as flow or ER diagrams. We are looking for ways to convert these diagrams into XML or other formats for representation. Are there any open-source soft ...