tags:

views:

38

answers:

2

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.

Gentlemen, 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.

+1  A: 

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');
    }
}
Nick Craver
@Nick Craver, `this.originalText` variable cannot store information between two onclick calls.
Kalinin
@Kalinin - Sure it can, in this context, `this` is the element you clicked on, *that's* where it's storing the text. Here's a demo of it working: http://jsfiddle.net/nick_craver/KrFuX/
Nick Craver
@Nick Craver, You're right, the solution works.
Kalinin
+1  A: 

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>
Golmote
@Golmote, Your solution works!
Kalinin
@Golmote, I like your solution, i try to tie it to my code (in which used event delegation).
Kalinin