Reuse the function in javascript

Asked

Viewed 150 times

0

Personal I am with the following doubt,wanted to manipulate a specific value in my function,where the assigned value is not fixed but dynamic(where I can change with form the need).

function mostrardiv() 
  {
      document.getElementById("teste").style.display = "block"; 
  }

In Document.getElementById the id it receives is test but I wanted to have the freedom that when calling the function in the code I can change the value that is assigned to Document.getElementById.

I searched on the subject,I only found how to use the prototype in javascript,however I still don’t understand how I can change the value assigned in Document.getElementByI.

The way I thought about it more like this:

function mostrardiv(val) 
  {
      document.getElementById(this.val).style.display = "block";
  }

But it didn’t work in html I used the function so:

 <div class="row" >
      <div class="col-md-2" onmouseover="mostrardiv('teste')" > <img class="img-responsive" src="_imagens/1.png" >
 </div>
  • Simple create an id in your div ex: id="minhaDiv" change the parameter to ex: mostrardiv(this) go to the function and change to val.id

  • Example: https://jsfiddle.net/sqosv654/

  • Another thing, as you are using bootstrap could already use jQuery right?

  • Yes ,but I’m still not confident with javascript ahahhahah,one question it just my function has declared in the same place as the id?

1 answer

2


It would be about the same as it is below, but the onmouseover="mostrardiv(this)" would have to be inside the element tag you want to catch the ID.

<div class="col-md-2" onmouseover="mostrardiv(this)" > 
    <img class="img-responsive" src="_imagens/1.png" > 
</div>

function mostrardiv(campo) 
{
  document.getElementById(campo.value).style.display = "block"; 
}
  • Did you test this solution before you answered? from what I’m seeing, if you use a selector per id it is expected that the id is in the tag and in your example there is no id.

  • test but as I showed I wrote wrong in the code, thank you very much worked as I wanted :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.