25054

Get clicked element's ID and include it in a function with pure JS?

I need to display different output according to each different icon clicked without defining separate functions;

HTML:

<p onclick="expand()" id="i1">icon1</p> <p onclick="expand()" id="i2">icon2</p> <p onclick="expand()" id="i3">icon3</p> <div id="blocki1"></div> <div id="blocki2"></div> <div id="blocki3"></div>

Can I do something like this with JS?

function expand() { document.getElementById("block" + this.id).style.display = "block"; }

I've tried the method above which apparently didn't work, I need to a)store icon's id and b) combine the id with string. Don't sure if that's possible.

Answer1:

<p onclick="expand(this.id) id="i1">icon1</p> <p onclick="expand(this.id) id="i2">icon2</p> <p onclick="expand(this.id) id="i3">icon3</p> <div id="blocki1"></div> <div id="blocki2"></div> <div id="blocki3"></div> <script> function expand(e) { document.getElementById("block" + e).style.display = "block"; }} </script>

Answer2:

First.. You have 4 typos. First 3 are that you don't have closing " after onclick="expand()

<p onclick="expand() id="i1">icon1</p> <!-- There needs to be " after expand() -->

Last typo is you have extra closing } after expand function.

Now, since you're not using addEventListener API, the value of this will not be set on your expand function. So you need to pass your current element as a parameter to the function.

<p onclick="expand(this)" id="i1">icon1</p> <p onclick="expand(this)" id="i2">icon2</p> <p onclick="expand(this)" id="i3">icon3</p> <div id="blocki1">blocki1</div> <div id="blocki2">blocki2</div> <div id="blocki3">blocki3</div>

(Added some place holder text to divs to see if this works)

Lastly, access the current element in your function as a first parameter.

function expand(el) { document.getElementById("block" + el.id).style.display = "block"; }

Answer3:

Pass parameters to the function

You need to pass some data (e.g. the reference to the object, its name, or whatever else you need) to the function you're calling.

For example, look at the sample code from https://www.w3schools.com/jsref/event_onclick.asp

<p onclick="myFunction(this, 'red')">Click me to change my text color.</p> <script> function myFunction(elmnt,clr) { elmnt.style.color = clr; } </script>

Answer4:

I might approach it slightly differently by removing the inline JS, and using classes and data attributes. Here I have classes and data attributes on all the elements. I attach click event listeners to the "buttons" which call the handleClick function. This function checks the data id attribute of the button and grabs the corresponding slide, adding a "show" class to its class list.

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

const buttons = document.querySelectorAll('.button');

buttons.forEach(button => {
  button.addEventListener('click', handleClick, false);
});

function handleClick(e) {
  const id = e.target.dataset.id;
  const slide = document.querySelector(`.slide[data-id="${id}"]`);
  slide.classList.add('show');
}
.slide {
  display: none;
}

.show {
  display: block;
}
<p class="button" data-id="1">icon1</p>
<p class="button" data-id="2">icon2</p>
<p class="button" data-id="3">icon3</p>
<div class="slide" data-id="1">blocki1</div>
<div class="slide" data-id="2">blocki2</div>
<div class="slide" data-id="3">blocki3</div>


Answer5:

Your code should like this

<p onclick="expand(this) id="i1">icon1</p> <p onclick="expand(this) id="i2">icon2</p> <p onclick="expand(this) id="i3">icon3</p> <div id="blocki1"></div> <div id="blocki2"></div> <div id="blocki3"></div> <script> function expand(elm) { document.getElementById("block" + elm.id).style.display = "block"; } </script>

Answer6:

If you are a beginner, I would suggest you to avoid practice of adding handlers in HTML, before it becomes your coding attitude.

Instead, add eventlisteners for them in js. Separation of concerns is really big theory.

And it's relativelyeasy to deal with this in event handlers

You can read more about it here

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

var ps = Array.from(document.querySelectorAll("p"));

for(var i=0; i< ps.length; i++){
  ps[i].addEventListener(("click"), function(){
   document.getElementById("block" + this.id).style.display = "block";
  })
}
div{
  display: none;
}
<p  id="i1">icon1</p>
<p  id="i2">icon2</p>
<p id="i3">icon3</p>
<div id="blocki1">This is 1</div>
<div id="blocki2">This is 2</div>
<div id="blocki3">This is 3</div>


Recommend

  • Creating lists of dynamic types
  • Gzipping Har Files on HDFS using Spark
  • Overriding method with a lower-visibility one results in compilation error
  • How would I create “multiple choice” columns in Local Database?
  • Android: ListAdapter example redraws same content
  • VBA, TRIM part of a Path
  • Picasso Taking time to load images
  • Dependable views in Ember
  • Galaxy S4 Android Custom Camera Issue
  • Avoid registering duplicate broadcast receivers in Android
  • Java making confirming exit
  • JSR-330 support in Picocontainer : @Inject … @Named(\"xxx)
  • Creating a DropDownList
  • Who propagate bugfixes across branches (corporate development)?
  • What does 'Language neutral' mean with regard to MAKELANGID?
  • Unable to decode certificate at client new X509Certificate2()
  • Excel's Macro-Recorder usage
  • C: Incompatible pointer type initializing
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • Needing to do .toArray() to get output of mongodb .find() on key name not value
  • How to use carriage return with multiple line?
  • How to define and use opencv mat of user type
  • Scrapy recursive link crawler
  • Disabling Alt-F4 on a Win Forms NotifyIcon
  • Cassandra Data Model
  • Symfony2: How to get request parameter
  • Weird JavaScript statement, what does it mean?
  • Adding custom controls to a full screen movie
  • ORA-29908: missing primary invocation for ancillary operator
  • PHP: When would you need the self:: keyword?
  • Acquiring multiple attributes from .xml file in c#
  • How to set the response of a form post action to a iframe source?
  • Getting Messege Twice Using IMvxMessenger
  • Change div Background jquery
  • need help with bizarre java.net.HttpURLConnection behavior
  • Qt: Run a script BEFORE make
  • Django query for large number of relationships
  • reshape alternating columns in less time and using less memory
  • Python/Django TangoWithDjango Models and Databases
  • How can I use threading to 'tick' a timer to be accessed by other threads?