Jeton R.
Jeton R.

Reputation: 395

jQuery undo click() function changes

I want to make some changes to the css and class on form input text fields, when users click the reply button and I got it working but then the form at the bottom stays with the changes. So my question: Is there any way to undo these changes and return the form to previous state ?

$(".comment-reply-link").click(function() {
    if($("#commentform").width() < 590){
        $("#commentform input[type='text']").css("margin-left","0");
        $("#commentform input[type='text']").removeAttr('class');
    }
})

Upvotes: 1

Views: 3840

Answers (3)

melc
melc

Reputation: 11671

This is an approach to store a cloned state with jquery's data and restore it whenever you want. Regardless of the number of changes you make to the element. For example,

http://jsfiddle.net/xr63r/

HTML

<div id="commentform">
    <input type="text" class="red-border" />
    <button class="comment-reply-link">test</button>
</div>
<button class="undo">undo</button>

JS

$(".comment-reply-link").click(function() {
    if($("#commentform").width() < 590){
        /*create a clone of the element you modify*/
        var theClone = $("#commentform").clone(true,true);
        /*add the cloned element to a data attribute for restoring the state*/
        $("#commentform").data("undo",theClone);

        /*any kind of css modifications may follow*/
        $("#commentform input[type='text']").css("margin-left","0");
        $("#commentform input[type='text']").removeAttr('class');
    }
})

$(".undo").click(function(){
/*if state undo exists, restore it*/
    if($("#commentform").data("undo")){
        var theClone = $("#commentform").data("undo");
        $("#commentform").replaceWith(theClone);
    }
});

CSS

/*this is an example css style related to a class*/
input.red-border{
    border:red 1px solid;
}

Upvotes: 0

redV
redV

Reputation: 684

AFAIK, There is no method available to store changes happened in the DOM and revert back when you want. You can achieve that like below

 $('.element').bind('click', plus10);
 $('.revertChange').bind('click', minus10);
 var input = $('#someInput');

 function plus10(){ 
      input.val(input.val() * 1 + 10); 
 }
 function minus10(){ 
      input.val(input.val() * 1 - 10); 
 }

If you are trying to add styles and revert make a class with necessary styles then toggle class

 .someClass{
      margin:10px;
      color:green;
      /* ...... */
 }

then toggle class on element like below

 $('element').toggleClass( "someClass" );

Upvotes: 2

nkmol
nkmol

Reputation: 8091

If you mean to undo the inline styles, well yes you can :

$("#commentform input[type='text']").css("margin-left","");

This will for example reset/undo your inline style of margin-left.

Upvotes: 0

Related Questions