Remove class using jQuery when clicked for the second time and also disable hover effect on the second click

I'm trying to implement a feature that removes the 'active' class when a checkbox is clicked for the second time, similar to how Pinterest handles checkboxes for Twitter and Facebook. Here's what I have tried so far:

$(".add_link_twitter.active").click(function(e) {  
      $(this).removeClass(activePostTwitter); 
    });

I have a couple of questions:

  1. How can I remove the 'active' css class on the second click of the checkbox?
  2. Is there a way to disable '.add_link_twitter:hover' when the Twitter checkbox is selected?

Any help would be greatly appreciated!

Here's the relevant jQuery code:

var postTwitter = ".add_link_twitter"; 
var activePostTwitter = "active"; 
$(postTwitter).click(function(e) {  
  $(this).addClass(activePostTwitter); 
});

Here's a snippet of the html:

<label class="add_link_twitter">
<input type="checkbox" name="publish_to_twitter" class="publish_to_twitter"><span>Share on Twitter</span>
</label>

And here's the related CSS styling:

.add_link_twitter{
    position:absolute;
    left:15px;
    bottom:16px;
    color: #a19486;
    border: 2px solid transparent;
    border-color: #F0EDE8;
    border-radius: 4px;
    font-size: 13px;
    font-weight: bold;
    cursor: pointer;
    padding: 7px;
    padding-top: 5px;
    padding-bottom: 5px;
}

.active {
    border-color: #468BD0;
    color: #468BD0;
    background-color: whiteSmoke;
}

.add_link_twitter:hover
{
    color: #A19486;
    border: 2px solid transparent;
    border-color: #C2B1A2;
    border-radius: 4px;
    background-color: white;
    padding: 7px;
    padding-top: 5px;
    padding-bottom: 5px;
}

Answer №1

Instead of

When clicking on the element with the class postTwitter, add the class activePostTwitter to it:
$(postTwitter).click(function(e) {  
  $(this).addClass(activePostTwitter); 
});

Try using:

When clicking on the element with the class postTwitter, toggle the class activePostTwitter on and off:
$(postTwitter).click(function(e) {  
  $(this).toggleClass(activePostTwitter); 
});

EDIT:

The click event seems to trigger twice due to event propagation. To solve this issue, assign the click handler to the input element within postTwitter and have it toggle the class of its parent instead:

Handle click events on the input element inside postTwitter and toggle the class activePostTwitter on its parent:
$(postTwitter + " input").click(function(e) {
    $(this).parent().toggleClass(activePostTwitter);
});

Check out a demo on jsfiddle: http://jsfiddle.net/bpfqB/

Answer №2

This solution is designed to address both of your inquiries:

$(function() {
    "use strict";
    var $postTwitter = $("label.add_link_twitter");

    $postTwitter.find("input:checkbox").click(function() {
        $(this).parent().toggleClass("active");
        if($("input.publish_to_twitter").is(":checked")) {
            $(this).parent().removeClass("hover");
        }
    });

    $postTwitter.hover(
        function() {
            if($("input.publish_to_twitter").is(":checked")) {
                return;
            }

            $(this).addClass("hover");
        },
        function() {
            $(this).removeClass("hover");
        });
});

Please note that adjustments must be made to your CSS for this to work, as hovering should be handled using jQuery instead of relying solely on CSS hover effects.

DEMO

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

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

Upon postback, the Jquery Chosen plugin dynamically creates a new section

I've integrated the Jquery Chosen plugin into my MVC application and everything is loading correctly at first. However, when I refresh a div on the page with data from the server using an ajax call, it ends up creating a duplicate section. Is there a ...

Is adding a property to a div using the Jquery Css Function taking longer than expected?

I am attempting to scale a div when another is clicked, with the scaling origin starting from where the click occurred. This is similar to Apple's behavior when you open an app and it expands from where you clicked. However, I'm facing an issue ...

Aligning radio button vertically in React using Bootstrap styling

I am struggling to align a radio button within a container inline with other buttons on the right. Can anyone provide guidance on how to resolve this issue? Here is my current setup: https://i.sstatic.net/SSWZe.png Code: import React, { Component } from ...

Troubleshooting problems with resizing images using CSS

I am experiencing an issue with resizing images that I have configured in the admin panel. .users-list>li img { border-radius: 50%; max-width: 100%;    height: auto;     width: 100px;     height: 100px; } When enlarged, the images l ...

Retrieve information from XML using jQuery

<?xml version="1.0" encoding="UTF-8"?> <slider> <csliderData1> <title>Kung Fu Panda</title> <content>In the Valley of Peace, Po the Panda finds himself chosen as the Dragon Warrior despite</content ...

AngularJS and JQuery validated

I'm looking to achieve something similar to what was discussed in this thread: Angularjs directive wrapping ng-repeat Although I can make it work as shown in the thread, I encounter an issue when updating the dirs array using Angular (for example, w ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

Sequential jQuery AJAX requests triggering in an incorrect sequence

One challenge I am facing involves a select list with bundles of short texts. Upon selecting a specific bundle, the texts are displayed in two tables. Each table row has a "Delete" icon to remove a text from the bundle. I am aiming to refresh both the tabl ...

Storing Documents on Your Device

I've been working on a project to create a web page that provides links to online PDF files. When you click on these links, the file should be saved locally and its name/path added to local storage. I then aim to display all the saved files by iterati ...

In AngularJS, enhance pagination loading by appending a $resource queried array to the end of another

I'm currently working on implementing a loading feature for my Angular application. The goal is to preload page 3 when a user navigates to page 2. Utilizing $resource, I'm querying the Posts resource using Post.query(). By calling Post.query({pa ...

Having trouble getting the libphonenumber npm package up and running, encountering an error stating that fs.readFileSync is not functioning properly

I am currently working on incorporating the googlei18n libphonenumber library for validating phone numbers. I have installed the npm package using npm i libphonenumber. However, when I try to use it like this: var libphonenumber = require('libphonenu ...

Deliver an intentionally bogus HTTP response using Express

I'm currently working on creating test cases for a web application and I am interested in testing how well the client can handle invalid HTTP responses. Can you provide some suggestions on how to purposely mess up a response so that it is no longer va ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

What could be the reason for the failure in my mocha/chai Error throwing test?

In my pursuit to test a simple javascript package, I encountered an issue. Despite wanting to verify if an Error is thrown during the test, it bizarrely gets marked as a failure when executed. Here's the snippet of code in question: var should = req ...

Is it possible to create a cross-sectional view of a lens using the HTML5 canvas element?

I am interested in creating a visual representation of the cross section of a lens element. Typically, these elements consist of one or two circular surfaces (front and back) with a rim of arbitrary shape. My goal is to simply connect the front and back su ...

Select2 - Issue with AJAX causing search results to not display in dropdown

Currently using Select2 version 4.0.1. Implemented ajax to display results based on user input, but facing an issue where Select2 does not list any results despite receiving the proper response from ajax. Additionally, the input box loses focus after the ...

Issue with Bootstrap Navbar dropdown causing page refresh instead of menu dropdown activation

<!DOCTYPE html> <html lang="en" dir="ltr" style="style.css"> <!-- All icons were courtesy of FlatIcon : www.flaticon.com and FreePik : www.freepik.com --> <head> <meta charset="utf-8"&g ...

Tips for updating the border color of a button:

Struggling to alter the border color of a button Attempting borderColor attribute proved futile: borderColor: '#FFFFFF' Anticipated result Code snippet: headerBtn: { backgroundColor: 'black', fontSize: '16px', f ...

Delay in loading Jquery accordion due to value binding

I've noticed that my jquery accordion takes a significant amount of time to collapse when the page initially loads. After some investigation, I realized that the issue lies in the fact that there are numerous multiselect listboxes within the accordio ...