DCR
DCR

Reputation: 15665

how to assign a js function to a class and get id when clicked

I'm working on a calculator and have a mousedown and mouseup function on every id. Is there some way to clean that up and have a function called anytime a class element is clicked and be able to get the id that's been clicked inside the function?

here's a link to a myfiddle calculator

also, I noticed that when I placed my javascript directly in the JS box it didn't work, however as a script embedded in the html it works fine. Could someone explain why?

 <tr>
    <td class='noborder' colspan='1' rowspan='2'> </td>
    <td id='1' class='buttons' colspan='4' rowspan='2' onmousedown="mouseDown(this.id)" onmouseup="mouseUp(this.id)" ;>1</td>
    <td id='2' class='buttons' colspan='4' rowspan='2' onmousedown="mouseDown(this.id)" onmouseup="mouseUp(this.id)" ;>2</td>
    <td id='3' class='buttons' colspan='4' rowspan='2' onmousedown="mouseDown(this.id)" onmouseup="mouseUp(this.id)" ;>3</td>
    <td id='plus' class='buttons' colspan='4' onmousedown="mouseDown(this.id)" onmouseup="mouseUp(this.id)" ;>+</td>
    <td class='noborder' colspan='1' rowspan='2'> </td>
  </tr>


<script>
function mouseDown(id) {
document.getElementById(id).style.backgroundColor = "gray";
}

function mouseUp(id) {
document.getElementById(id).style.backgroundColor = "white";
}
</script>

Upvotes: 0

Views: 211

Answers (3)

Leonid
Leonid

Reputation: 738

I realized a way how to add mousedown and mouseup events on all the elements with a class:

var elements = document.getElementsByClassName("buttons");
for (var i = 0; i < elements.length; i++) {
    elements[i].onmousedown = function() {
        mouseDown(this.id);
        mouseUp(this.id);
    }
}

I tested it on w3schools.com.

(Also, I don't know what you mean by JS Box. Sorry.)

Upvotes: 1

bgauryy
bgauryy

Reputation: 416

Remove the script tag, and add this to your css style:

   .buttons:active {
    background-color: gray;
   }

For calculations use something like this:

<script>
var table = document.getElementsByTagName("table")[0]
table.addEventListener("click",clicked);

function clicked(el){
  if (el.hasClass("buttons")){
   //magic
}
}
</script>

Upvotes: 0

harryg
harryg

Reputation: 24077

It might be because you have an id conflict on the page. Using IDs like "1" is not recommended for this reason; better to be more specific.

In fact, there is no need to query the element by its ID anyway. You can operate directly on the element by just passing it into the handler. E.g.

<td class='buttons' onmousedown="mouseDown(this)" onmouseup="mouseUp(this)" >1</td>

<script>
function mouseDown(element) {
  element.style.backgroundColor = "gray";
}

function mouseUp(element) {
  element.style.backgroundColor = "white";
}
</script>

EDIT: As @bgaury mentioned, a CSS active pseudo class is a far better option for this use case however.

Upvotes: 0

Related Questions