"Enhance the styling with jQuery's css() function when clicked

I am currently working on the following code:

 $(document).ready(function(){
    $("#FlatCheckbox").click(function(){
        $("#style1").css("margin-top",10);
    });
});
 <h2>
       <input type='checkbox' id="FlatCheckbox" class="FlatCheckbox" onClick=''>
          AAA
 </h2>

<div id='style1'>
      <input type='button' onClick='' class='AddBtn' value='Apply / Save'>
</div>

My query is:
How can I reset the button's css back to its original state after clicking the checkbox again?

Answer №1

It is recommended to use the toggleClass() method instead of applying inline styles directly.

$(document).ready(function() {
  $("#FlatCheckbox").click(function() {
    $("#style1").toggleClass('clicked', this.checked);
  });
});
.clicked {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
       <input type='checkbox' id="FlatCheckbox" class="FlatCheckbox" onClick=''>
          AAA
 </h2>

<div id='style1'>
  <input type='button' onClick='' class='AddBtn' value='Apply / Save'>
</div>

Answer №2

It is recommended to utilize toggleClass in this scenario

$("#FlatCheckbox").click(function() {
    $("#style1").toggleClass("active");
});

Check out the Fiddle

Answer №3

Check out this solution using a boolean flag:

$(document).ready(function(){
var toggle = true;
    $("#FlatCheckbox").click(function(){
        if(toggle) {
            $("#style1").css("margin-top",10);
        } else {
            $('#style1').css('margin-top',0);
        }  
        toggle = !toggle;
    });
});

Answer №4

To achieve a margin-top property exclusively, you can utilize the following JavaScript code:

    $(document).ready(function(){
        var i=0;
        $("#FlatCheckbox").click(function(){
           if(i++%1==0)
            $("#style1").css("margin-top",10);
           else
            $("#style1").css("margin-top",0);
        });
    });

Alternatively, you can use toggleClass method like this:

 $(document).ready(function() {
   $("#FlatCheckbox").click(function() {
     $("#style1").toggleClass('marginable', this.checked);
   });
 });

Remember to define the following CSS for the 'marginable' class:

.marginable{margin-top:10px}

Answer №5

Take a look at @AnoopJoshi's response. If you wish to modify the style, you can create your own toggle using a boolean flag.

$(document).ready(function () {


  var isToggled = false;

  $("#FlatCheckbox").click(function() {
    isToggled = !isToggled;
    $("#style1").css("margin-top", isToggled ? 10 : 0);
  });
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<h2><input type='checkbox' id="FlatCheckbox" class="FlatCheckbox" onClick=''>AAA</h2>

<div id='style1'>
  <input type='button' onClick='' class='AddBtn' value='Apply / Save'>
</div>

Answer №6

To implement a new margin, you can utilize the .toggleClass('newMargin') method.

.newMargin{
    margin-top : 10
}

Alternatively, you can use the following jQuery script:

$(document).ready(function(){
    var initMargin = $("#style1").css("margin-top");
    $("#FlatCheckbox").click(function(){
        var currentMargin = $("#style1").css("margin-top");
        $("#style1").css("margin-top",currentMargin == initMargin? "10px": initMargin);
    });
});

The complete JavaScript and HTML code is as follows:

$(document).ready(function(){
    var initMargin = $("#style1").css("margin-top");
    $("#FlatCheckbox").change(function(){
      debugger;
        var currentMargin = $("#style1").css("margin-top");
        $("#style1").css("marginTop",currentMargin == initMargin? "10px": initMargin);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <h2>
       <input type='checkbox' id="FlatCheckbox" class="FlatCheckbox" onClick=''>
          AAA
 </h2>

<div id='style1'>
      <input type='button' onClick='' class='AddBtn' value='Apply / Save'>
</div>

Answer №7

There is no predefined function called .toggleCss(), but you can achieve similar functionality using the [toggleClass][1] method as shown below:

$(document).ready(function(){
        $("#FlatCheckbox").click(function(){
            $("#style1").toggleClass("styled");
        });
});
.styled{
  margin-top:10px;
  background-color:blue;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>
  <input type='checkbox' id="FlatCheckbox" class="FlatCheckbox">
  AAA
</h2>

<div id='style1'>
  <input type='button' class='AddBtn' value='Apply / Save'>
</div>

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

Syntax error in Ajax password recovery

Currently, I am facing a syntax error with a form that I recently converted from PHP to utilize Jquery/Ajax. My main goal is to test the functionality of the form to ensure it can successfully submit and reset passwords. The specific error message I keep ...

Tips for creating an HTML page with the dimensions of an A4 paper sheet?

My goal is to display the HTML page in a browser while containing the content within the dimensions of an A4 size page. Additionally, when printed, the HTML page should be formatted to fit onto A4-sized paper pages. <div classNa ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

Click on the entire table to be redirected to the specified link

Currently, I am facing an issue with styling my tables as links. I have 3 tables and I want each table to be a clickable link. However, after implementing the links, I am unable round the corners of the tables. I envision the final look to be similar to t ...

Validating forms using Ajax in the Model-View-Controller

I am facing an issue with my Ajax form, where I need to trigger a JavaScript function on failure. The code snippet looks like this: using (Ajax.BeginForm("UpdateStages", new AjaxOptions { HttpMethod = "POST", OnSuccess = "refreshSearchResults(&apo ...

Card carousel rotation

Apologies for the vague title, I'm unsure how to properly label my issue. I have a section set up with cards, but I'm aiming to create something resembling a menu that functions like a carousel. Essentially, I want to include right and left arro ...

Unlock the power of Bootstrap CDN with these easy steps!

I am currently trying to incorporate a CDN for Bootstrap in order to enhance the performance of my website. Surprisingly, directly referencing the CSS works perfectly fine but using the CDN does not. Could someone provide me with guidance on how to resolv ...

Dynamic Date from Week Number using AJAX in PHP

I am in the process of developing a work scheduler and I need to navigate through the weekly calendars. I have the current week displayed and when the left double arrow is clicked, I extract the week number of the displayed week and pass it to the controll ...

What is causing the customer's email address to not be properly linked with Stripe?

Currently, I have set up a simple custom button Stripe Checkout that is functioning fine for processing payments. However, I am facing an issue where I cannot retrieve the customer's email address to pass back to Stripe. Below is my existing code: J ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Is there a way to utilize JavaScript and AJAX to save a WordPress cookie and log in a user, all without the need for any plugins?

My goal is to log in to WordPress using only ajax requests. Here's the code I have so far: var username = data.username; var password = data.password; var wp_login_url = "http://local_Ip/api/user/generate_auth_cookie/?username=" +username + "&pas ...

Utilizing CSS to target the ID of an anchor element

I am a beginner in the world of HTML and CSS. I recently attempted to target an element using an id selector in my CSS code, but unfortunately, it did not work as expected. Can someone shed some light on why this might be happening? <!DOCTYPE html> ...

The JQuery error encountered was due to a missing colon after the property ID

I'm currently working on some jQuery code that is supposed to hide one paragraph and show another when a specific action is triggered. I have created a class called "showp" which displays the targeted paragraph while ensuring that other paragraphs are ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Java script pop-up notifications always show up

This Text Goes Above the Form <?php require_once "core-admin/init-admin.php"; if( !isset($_SESSION['admin_username']) ){ $_SESSION['msg'] = 'page cannot be opened'; header('Location:admin_login.php&ap ...

Is there a way to incorporate external HTML files into my webpage?

Looking to update an existing project that currently uses iFrames for loading external HTML files, which in this case are actually part of the same project and not from external sites. However, I've heard that using iFrames for this purpose is general ...

Issue with Bootstrap 4 tab.js not updating active states

I am having trouble with 2 out of the 4 tab.js examples in both CodePen and a local HTML file. The "nav" example is causing the items in the dropdown to stay active and inaccessible after clicking. The same issue occurs with all the items in the vertical t ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

Struggling to change h2 style on WordPress?

In a WordPress page, I create three heading texts and adjust the CSS when the screen width is less than 820px. Here is the code snippet: <h1 class="block-h1">Heading 1</h1> <h2 class="block-h2">Heading 2</h2> <h3 class="block-h3 ...

Scrolling background for a nested Bootstrap modal

I am facing an issue with a modal that has a lengthy content and a button to open another modal. Once the inner modal is closed, the outer modal becomes unresponsive. It fails to scroll and instead, the background starts to scroll. While I have come acros ...