views:

51

answers:

2

Hi,

I am using sizzle to select various parts of the DOM.

My code is below. The problem is that the onmouseup event is being triggered when the page is loaded instead of when the user interacts with the page.

Can someone explain why this is please.

Thanks.

// Effects object
var effects = {
    // Display an object
    show : function(obj) {
        obj.style.display = 'block';
    },
    // Hide an object
    hide : function(obj) {
        obj.style.display = 'hide'; 
    },
    // Toggle
    toggle : function(obj) { 
        if (obj instanceof Array) {
            alert('array');
        } else {
            alert('single');    
        }
    }
}

// Selector Class
var s = Sizzle;

window.onload = function() {
    s('#toggle-content').onmouseup = effects.toggle(s('.hidden-content'));
}

HTML as requested:

<div class="page-content box create-page">
    <h1><span class="left">Create Page</span><a class="right" id="toggle-content" href="#">Expand</a></h1>
    <div class="hidden-content">
        ...
    </div>
</div>
+1  A: 

It's because you're calling effects.toggle in the expression. You should actually bind the function to avoid calling it.

  function bind() {
    var initArgs =  array(arguments);
    var fx =        initArgs.shift();
    var tObj =      initArgs.shift();
    var args =      initArgs;
    return function() {
      return fx.apply(tObj, args.concat(array(arguments)));
    };
  }
  function array(a) {
    var r = []; for (var i = 0; i < a.length; i++)
      r.push(a[i]);
    return r;
  }

window.onload = function() {
    s('#toggle-content').onmouseup = bind(effects.toggle, null, s('.hidden-content'));
}
Delan Azabani
This triggers a javascript error. 'array is not defined'
JasonS
Fixed now. Sorry about that!
Delan Azabani
+3  A: 

you need to pass it as an anonymous function eg.

window.onload = function() {
    s('#toggle-content').onmouseup = function(){effects.toggle(s('.hidden-content'));}
}
matpol
This is what I had tried originally. It doesn't do anything. No errors and nothing alerted in the browser.When I move the annoymous function to a named function. Then have.s('#toggle-content').onmouseup = toggle();It still triggers when the page is loaded.
JasonS
doing it like this you do not need the brackets - this is why you use the anonymous function so you can pass the parameters.
matpol