Devesh Kumar
Devesh Kumar

Reputation: 1019

How to call a Javascript function when value of a variable changes?

Usually we call a Javascript function, when a button is click.

<button onclick=function1();>Post message</button>

Or sometimes, we may call a Javascript function at a particular time.

window.onload = myFunction();
          function myFunction()
           {
                 setInterval(function1,t);  
           }

where function1() is any Javascript function. I want to call this function only if value of a variable changes in the script.

For instance: Lets say I have a variable abc. Now value of that variable changes when I select something on the page using the function below.

var abc = function getSelectionHTML() {
      var userSelection;
      if (window.getSelection) {
        // W3C Ranges
        userSelection = window.getSelection ();
        // Get the range:
        if (userSelection.getRangeAt) {
          if (userSelection.rangeCount > 0)
        var range = userSelection.getRangeAt(0);
          else
        return '';
        } else {
          var range = document.createRange ();
          range.setStart (userSelection.anchorNode, userSelection.anchorOffset);
          range.setEnd (userSelection.focusNode, userSelection.focusOffset);
        }
        // And the HTML:
        var clonedSelection = range.cloneContents ();
        var div = document.createElement ('div');

        div.appendChild (clonedSelection);
        return div.innerHTML;
      } else if (document.selection) {
        // Explorer selection, return the HTML
        try {
          userSelection = document.selection.createRange ();
          return userSelection.htmlText;
        } catch (err) {
          return '';
        }
      } else {
        return '';
      }
    }

How to alert(abc) only when the value of variable changes? Please help!

Upvotes: 3

Views: 6595

Answers (2)

Lewis
Lewis

Reputation: 14866

Firstly, you need to define your variable abc with Custom Setters and Getters:

var value_of_abc;
 Object.defineProperty(window, 'abc', {
    get: function() {
      console.log('get!');
      return value_of_abc;
    },
    set: function(value) {
      console.log('set!');
      value_of_abc = value;
    }
  });

Then whenever you call or change variable abc, the thing down here will occur.

window.abc //get!
window.abc = 1 //set!

Upvotes: 2

CAFxX
CAFxX

Reputation: 30301

If you are targeting "modern" browsers, you can use Object.defineProperty to define a setter function, i.e. a function that get's called every time you set the value of the corresponding field.

Since "global" variables in JS are simply members of the window object jou should be able to do something like

Object.defineProperty(window, "abc", { set: function(v) { 
  /* this is run every time abc is assigned a value: 
     the value being assigned can be found in v */
} } );

Upvotes: 2

Related Questions