0

I implemented a moveable div function in JS (moveableFunc). I used onclick="moveableFunc(event ,this)" for each div (or element) to move it. I prefer to use this function as a attribue and the code would be as follow:

<div id="div1" data-option="moveable" class="div1">
    hello
</div>

How can I do it?

user2004403
  • 193
  • 2
  • 13

1 Answers1

1

You could bind the click event in window.onload only for elements with that attribute, like:

window.onload = function () {
    var moves = document.querySelectorAll('[data-option="moveable"]');
    for (var i = 0; i < moves.length; i++) {
        moves[i].onclick = function (e) {
            e = e || window.event;
            moveableFunc(e, this);
        };
    }
};

You could even change the selector to be .querySelectorAll('div[data-option="moveable"]'); if you know this will only be targeting <div>s, so it will speed up the search.

Or if you were able to restructure your moveableFunc's parameters to be:

function moveableFunc(e) {
    // Use `this` to reference the element that was clicked
}

Then you could just use the following to bind the event in the loop:

moves[i].onclick = moveableFunc;

Of course, it could be preferable to use addEventListener instead of onclick to bind the events. Here's some information on that: addEventListener vs onclick

References:

And just as an example, with jQuery, it could be done like:

$('[data-option="moveable"]').on("click", moveableFunc);

(where you modified the parameters of moveableFunc like I said before)

Community
  • 1
  • 1
Ian
  • 50,146
  • 13
  • 101
  • 111
  • **+1** event if i would be more strict and say it **is** preferable to use `addEventListener` instead of `onclick` because using the `on... =` always has the risk that you overwrite an already set callback somewhere else with out noticing it. – t.niese Apr 25 '13 at 06:48
  • @t.niese Very true. The majority of the time, you should use `addEventListener`, but although there probably are others, there's no reason to assume there's other event handlers. Anyways, I agree, and I added a link that explains differences - it's not really necessary for me to explain it more than providing that link – Ian Apr 25 '13 at 06:51
  • I tried the 1st option (for now), and after the 2nd line, I get: moves.length=0. The html code was: – user2004403 Apr 25 '13 at 08:11
  • I wrote: "window.onload = init();" in the header of index.html. init() has the code of "function" above. I found out that init() runs before the body created (firebug). Why does it happens? – user2004403 Apr 25 '13 at 09:07