0

When I click on any of the buttons, it tells me showElement is not defined.I'm looking to create a reusable function called showElement which can be called whenever I want to show a div by passing an id of that div. What am I doing wrong? https://jsfiddle.net/2taswyy6/20/

This is my html:

<button onclick="showElement('div1')">
Show Div 1
</button>
<button onclick="showElement('div2')">
Show Div 2
</button>

<div hidden id="div1">Showing Div 1</div>
<div hidden id="div2">Showing Div2</div>

updated: This is my jQuery:

  function showElement(id){
    $('#'+id).show()
  }
Boki_LV
  • 21
  • 1
  • 8
  • Why is that function within document ready? – Kevin B Feb 28 '18 at 00:19
  • 1
    `showElement` is a private function inside the document ready. It is not on the global scope for the inline bindings to access it. It will be undefined for the inline bindings. – Taplar Feb 28 '18 at 00:20
  • @KevinB does it need to be within a document ready? – Boki_LV Feb 28 '18 at 00:20
  • @Boki_LV If it doesn't depend on the document being ready, there's no reason to delay defining it. – Kevin B Feb 28 '18 at 00:21
  • @KevinB thanks for providing the links and all your input but I took it out of document ready and it still tells me that it is not defined. See here https://jsfiddle.net/2taswyy6/39/ – Boki_LV Feb 28 '18 at 00:34

2 Answers2

0

HTML:

<button onclick="showElement('div1')">
Show Div 1
</button>
<button onclick="showElement('div2')">
Show Div 2
</button>

<div style="display:none" id="div1">Showing Div 1</div>
<div style="display:none" id="div2">Showing Div2</div>

jQuery:

function showElement(id){
  $('#'+id).show()
}
Boki_LV
  • 21
  • 1
  • 8
-1

Use Global data-*

You can use html global data-* on every button as an attribute to identify the id for the div to be shown. Here is an example:

HTML:

<button data-div-id="1" class="button">Show Div 1</button>

More: w3schools.

Solution:

Here is the solution of your question using jQuery on Codepen.

If you want to toggle the div here is another example on Codepen

PS:

Change css from visibility: hidden; to display: none; if you want to hide it totally.

More: StackOverflow

Hope this helps.

Community
  • 1
  • 1
Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24