Question

I am setting up a lightweight website for my work. It has very little JS interactivity, using only GSAP with TweenLite() for 1-2 animations. Since its nearly all unique elements, I can mostly use getElementById() to cover them.

One problem involving multiple similar elements is causing me grief. An accordion style menu:

<button>MenuOne</button>
<div>
    <a>...</a>
    <a>...</a>
    <a>...</a>
</div>

<button>MenuTwo</button>
<div>
    <a>...</a>
    <a>...</a>
    <a>...</a>
</div>

<button>MenuThree</button>
<div>
    <a>...</a>
    <a>...</a>
    <a>...</a>
</div>

The idea is on the click of the Menu button, the next div becomes visible, and any over divs become invisible (all hidden by default).

If I were to use jQuery, this could be achieved by

$('button').click(function() {

  //show/hide stuff

});

I don't want to use jQuery for a single selector, when GSAP covers all the animations I've used so far:

var btn = document.getElementsByTagName('button');

btn.onmouseup=function () {

  //show/hide stuff

};

However, this doesn't seem to react to me clicking the buttons (no errors, nothing). I have the same function() inside, and can get it to work by putting the btn variable into jquery $(btn).click(.

I can only assume the btn variable is watching all buttons, and cannot distinguish which one (if any) I've just clicked. Something that jQuery library is able to do.


Hunting around online, I've found that the native JS result is slightly different to the jquery one. In the console, jquery shows up as an Object[array], and javascript shows as an HTMLCollectionT[array]. My guess is part of the jquery array has some marker that isn't there by default.

I found how to pick [0] [1] [2] buttons in the array and can add unique IDs, but am sure I can solve this without 3 separate functions.

Was it helpful?

Solution

You will get the list of buttons by document.getElementsByTagName() function, if you want to attach particular function at click of particular button then you can do like this.

var allButtons = document.getElementsByTagName('button');
for(var i=0; i<allButtons.length; i++){
    allButtons[i].onclick = myfunction;
}

function myfunction (){
    alert(this.id);
}

Here is the demo with http://jsfiddle.net/M697C/

OTHER TIPS

The jQuery binding will automatically loop through all of the captured elements, and manually bind to each one. When you are using vanilla JS, you have to do the looping yourself:

var btn = document.getElementsByTagName('button');

for (var i = 0; i < btn.length; i++) {
    btn[i].onmouseup = function () {
        // show/hide code here.
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top