1

I am attempting to get two functions to trigger with one button. Could someone help me what I did wrong?

I know that I can just add the text from function one from function two, but my goal was to complete two functions under one button.

<p id="demo" style="display:none">JavaScript can show hidden HTML elements.</p>

<p id="demoTwo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'" onclick="document.getElementById('demoTwo').style.display='block'">Click Me!</button>

I was wanting both function’s text to appear at the button click. However, only the first function completed.

1
  • Element attributes must be uniqe, you cannot have two onclick handlers. You can do this in one onclick handler onclick="document.getElementById('demo').style.display='block';document.getElementById('demoTwo').style.display='block'". Commented Jul 9, 2019 at 23:26

1 Answer 1

2

You need to add a function to be able to do that:

onclick="showDemos()"

Then in your JavaScript:

function showDemos() {
  document.getElementById("demo").style.display = "block";
  document.getElementById("demoTwo").style.display = "block";
}

function showDemos() {
  document.getElementById("demo").style.display = "block";
  document.getElementById("demoTwo").style.display = "block";
}
<p id="demo" style="display:none">JavaScript can show hidden HTML elements.</p>

<p id="demoTwo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="showDemos()">Click Me!</button>

Inline listeners are generally discouraged - you should use addEventListener:

function showDemos() {
  document.getElementById("demo").style.display = "block";
  document.getElementById("demoTwo").style.display = "block";
}

document.getElementById("button").addEventListener("click", showDemos);
<p id="demo" style="display:none">JavaScript can show hidden HTML elements.</p>

<p id="demoTwo" style="display:none">Hello JavaScript!</p>

<button type="button" id="button">Click Me!</button>

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need a function to do this, but it's certainly a good suggestion.
The teacher wasn’t allowing us to us external files yet. Thanks for the info!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.