Kalinin
Kalinin

Reputation: 2519

Remember the original state before "click"

There is a button (actually a lot of them), it has an event handler:

el.onclick = function(){
    if(this.className.indexOf("minimized") != -1){
        this.firstChild.nodeValue = 'turn back';
        this.className = this.className.replace("minimized", 'expanded');
    }
    else if(this.className.indexOf("expanded") != -1){
        this.firstChild.nodeValue = 'what was there before the first click';
        this.className = this.className.replace("expanded", 'minimized');
    }
}

Handler changes the state of the button.

What is the standard way (pattern) to memorize a text node before the first click on current button and return it on the second click (on the same button)?


Can you remember text node in a javascript variable, and not used for storing information HTML elements?

Without the use of global variables.

Upvotes: 0

Views: 545

Answers (2)

Golmote Kinoko
Golmote Kinoko

Reputation: 946

You could use a function ?

<div id="test" class='minimized'>what was there before the first click</div>

<script type="text/javascript">
function f(el) {
    var val = el.firstChild.nodeValue;
    return function() {
        if(this.className.indexOf("minimized") != -1){
            this.firstChild.nodeValue = 'turn back';
            this.className = this.className.replace("minimized", 'expanded');
        }
        else if(this.className.indexOf("expanded") != -1){
            this.firstChild.nodeValue = val;
            this.className = this.className.replace("expanded", 'minimized');
        }
    }
}

window.onload=function() {
    var el = document.getElementById('test');
    el.onclick = f(el);
}
</script>

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630627

You can create a property on the element itself, for example:

el.onclick = function(){
    if(this.className.indexOf("minimized") != -1){
        this.originalText = this.firstChild.nodeValue; //store original
        this.firstChild.nodeValue = 'turn back';       //change it
        this.className = this.className.replace("minimized", 'expanded');
    }
    else if(this.className.indexOf("expanded") != -1){
        this.firstChild.nodeValue = this.originalText; //restore it
        this.className = this.className.replace("expanded", 'minimized');
    }
}

Upvotes: 1

Related Questions