Using jQuery to toggle an open and close button

My icon functions as an open/close button. When opened, it turns red and rotates 45 degrees. The issue arises when trying to close it. Changing the div class causes the icon to disappear while in its active state. Below is the jQuery code I am using:

$(".fa-plus").click(function() {
  $(".form").removeAttr("style");
  $('.fa-plus').css('-webkit-transform', 'rotate(45deg)');
  $('.fa-plus').css('-webkit-transition', '0.25s');
  $('.fa-plus').css('color', '#FF0000');
  $(".fa-plus").attr("id", "test");
});

This function opens the icon and adds an ID called "test". Clicking on the icon with ID "test" does not display an alert, only clicking on the "+" symbol does.

$("#test").click(function() {
  alert('test');
});

Here's a demo. I only want the alert to appear when clicking on the red X symbol.

Answer №1

One way to achieve this is by following these steps: http://jsfiddle.net/M5N9V/2/

$(".fa-plus").click(function () {

    var io = this.io ^= 1;

    $(this).css({
        transform: "rotate("+ (io?45:0) +"deg)",
        color: io?"#f00":"#69f",
        transition:"0.25s"
    });

    if(io){
       // Add logic here for opening dropdown
    }else{
       // Add logic here for closing dropdown
    }

});

Another option is: http://jsfiddle.net/M5N9V/3/

$(".fa-plus").click(function () {
    $(this).toggleClass("fa-red");
});

To make it work, you can update your CSS like so:

.fa-plus {
    cursor: pointer;
    font-size: 24px;
    color: #69f;
    transition: 0.25s;
}
.fa-red{
    color: #f00;
    transform : rotate(45deg);
}

Answer №2

Check out this interactive demo...

The recommended approach involves using a CSS class and toggling it with each click event using jQuery's toggleClass function. Then, you can check if the class is present and take appropriate action:

JavaScript/jQuery:

$(".fa-plus").click(function() {
    $(this).toggleClass('fa-close');

    if(!$(this).hasClass('fa-close'))
        alert('closing!');
});

CSS:

.fa-plus {

    cursor: pointer;
    font-size: 24px;
    color: #6699FF;

    -webkit-transition:0.25s;
    -moz-transition:0.25s;
    -o-transition:0.25s;
    transition:0.25s;

}

.fa-close{

    -webkit-transform:rotate(45deg);
    -moz-transform:rotate(45deg);
    -o-transform:rotate(45deg);
    transform:rotate(45deg);

    color:#FF0000;

}

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

Automatically insert nested object keys and values from jQuery into their respective div elements

Below is a sample object that I am working with: "experience": { "1": { "jobtitle": "job_title", "companyname": "company_name", "companytown": "company_town", "companycountry": "company_country", "summary": "Sum ...

determining the sorting behavior of columns in Datatables

While working on my table, I referred to a Datatbles tutorial that covers sorting the third column as a percentage value. // Setting up column search - adding a text input to each footer cell $('#p_table-id tfoot th').each(function ...

How can I update the version of v8 in NodeJS to ensure I have the latest Javascript enhancements?

Is it possible to upgrade the JavaScript engine version from 3.x to 6.x without updating the Node.js version? The current Node version is 0.12.x. ...

The LoopBack framework encountered an issue where it could not execute the 'post' method due to being undefined

As a newcomer to loopback and node.js, I have successfully created two models - Rating and RatingsAggregate. Utilizing the loopback explorer, querying and posting against the API has been smooth. In an attempt to establish basic business logic, I am curre ...

The absence of a semicolon in the JSON file is causing VSCode to overlook the problematic line

I'm encountering an issue while attempting to load this compact JSON file into another webpage "data": [ { "id": 72053645, "name": "Weather Report", "type": "Flip ...

Using CSS, I have rearranged the content of a single row (tr) in an HTML table into two separate rows

I am currently facing a challenge with rearranging my table due to width constraints. My goal is to apply Jquery functions to the table in order to extract all parameters related to a product, but I want to avoid having nested tr elements or splitting para ...

What is the best way to display data retrieved from a GET request in Angular?

Spending too much time on a development issue is causing me frustration. After extensive research, I find myself stuck at this point. The problem lies in making a GET request from a service which is called by a controller. Below is the code for the servi ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

Display loading icon in AngularJS during template retrieval

Imagine I have this specific directive: angular .module('app.widgets') .directive('myCalendarRange', myCalendarRange); function myCalendarRange () { var directive = { link: link, templateUrl: '/template/is/located ...

Combining php with jquery

This message contains a successful integration of PHP code within jQuery using the AJAX method. However, there are errors encountered which may be due to my lack of experience in jQuery. Uncaught ReferenceError: save_customer is not defined Uncaught Synt ...

Arranging divs using inline-block display. How to adjust the heights consecutively?

After much searching and attempting, I am still unable to achieve a simple task. My goal is to apply display inline-block to some divs while aligning them in a row, similar to the image below: https://i.sstatic.net/iLhLS.png The issue arises when number ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

Trigger an event in Vue with specified parameters

I am attempting to emit a function with parameters in the following way. template: ` <div class="searchDropDown"> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup=" ...

Retrieve the scope object using angular.element and the $ID parameter

In order to transfer data from an angular application to scripts that operate outside of angular, I am seeking a solution since I cannot modify the code of the angular app. By utilizing Angular Batarang and NG-Inspector extensions in Chrome, I have identi ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Trying to align a Material UI button to the right within a grid item

I'm attempting to right float the button below using material-ui, but I'm unsure of how to achieve this: <Grid item xs={2}> <Button variant="contained" color="secondary&quo ...

How to send configuration data to an external library in Angular 6 in the app.module.ts file

My goal is to provide basic configuration settings to an external or third-party module. These settings are stored in a JSON file for easy modification across different environments without the need to rebuild the code. import { BrowserModule } from &apos ...

A pair of floating divs sandwiching a stretchy div in the middle

I am looking to achieve a fixed width header with specific layout requirements: A left-aligned div of variable width. A right-aligned div of variable width. An h2 element centered between the two divs, adjusting its size based on available space. The co ...

A step-by-step guide on using Jquery to fade out a single button

My array of options is laid out in a row of buttons: <div class="console_row1"> <button class="button">TOFU</button> <button class="button">BEANS</button> <button class="button">RIC ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...