/    Sign up×
Community /Pin to ProfileBookmark

How to get the index of e.target

I am trying to get the index of something I click. How can I do that?
This is what I tried

[code]
dots.forEach(dot =>
dot.addEventListener(“click”, e => {
const findIndex = e.target.index;

console.log(findIndex);

counter = findIndex;

sections.forEach((section, index) => {
if (counter === index) {
toggleText(index, “show”);
updateDot(index, “activeDot”);
section.scrollIntoView({ behavior: “smooth” });
}
});
})
);
[/code]

Also this is the project: https://codepen.io/raul-rogojan/pen/KKPBpXJ?editors=0010

to post a comment
JavaScript

12 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERSep 14.2019 — I'm not sure this is what you want, but I'll let you decide if it's for you.

It does not show a target index as I'm not sure what that is.

It does show the index within the element.

The original only showed the image index, but I expanded it to show a <li> and <table> position index

Ignore code if of no use to you :)

<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/&gt;
&lt;title&gt; Position Picker &lt;/title&gt;
&lt;!-- Modified from: https://javascriptsource.com/getposition-2/ --&gt;

&lt;style&gt;
.ptr { cursor:hand; cursor:pointer; }

table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #ddd;
}
th {
border: 1px solid black;
text-align: center;
padding: 2px;
width: 5em;
}
th:hover { background: lime; }
td {
border: 1px solid black;
text-align: right;
padding: 2px;
}
td:hover { background: orange; }
tr:nth-child(even){background-color: #d2d2d2; } /* for table stripes */

#fs1, #fs3 { width: 25%; float: left; }
#fs2 { width: 60%; }
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;fieldset id='fs2'&gt; &lt;legend&gt;Image positions&lt;/legend&gt;
&lt;div&gt;
&lt;p&gt;Click on a graphic below (these are in a different container from the ones above):&lt;/p&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix1-sm-1.gif' onClick="showImagePick(this)" /&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix2-sm-3.gif' onClick="showImagePick(this)" /&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix3-sm-1.gif' onClick="showImagePick(this)" /&gt;
&lt;br&gt;&lt;input id="imgNo" value="" size="30em"&gt;
&lt;/div&gt;
&lt;/fieldset&gt;

&lt;fieldset id='fs1'&gt; &lt;legend&gt;List positions&lt;/legend&gt;
&lt;p&gt;Click on a list item below:&lt;/p&gt;
&lt;ol&gt;
&lt;li onClick="showListPick(this)" class="ptr"&gt;This is an ordered list.&lt;/li&gt;
&lt;li onClick="showListPick(this)" class="ptr"&gt;Click on any item in the list.&lt;/li&gt;
&lt;li onClick="showListPick(this)" class="ptr"&gt;JavaScript can get its position!&lt;/li&gt;
&lt;li onClick="showListPick(this)" class="ptr"&gt;Very useful for dynamic lists.&lt;/li&gt;
&lt;/ol&gt;
&lt;input id="lstNo" value=""&gt;
&lt;/fieldset&gt;


&lt;!-- Original version
&lt;p&gt;Click on a list item below:&lt;/p&gt;
&lt;ol&gt;
&lt;li onClick="showLstPick('Item '+GetPosition(this.parentNode,this))" class="ptr"&gt;This is an ordered list.&lt;/li&gt;
&lt;li onClick="showLstPick('Item '+GetPosition(this.parentNode,this))" class="ptr"&gt;Click on any item in the list.&lt;/li&gt;
&lt;li onClick="showLstPick('Item '+GetPosition(this.parentNode,this))" class="ptr"&gt;JavaScript can get its position!&lt;/li&gt;
&lt;li onClick="showLstPick('Item '+GetPosition(this.parentNode,this))" class="ptr"&gt;Very useful for dynamic lists.&lt;/li&gt;
&lt;/ol&gt;

&lt;div&gt;
&lt;p&gt;Click on a graphic below (these are in a different container from the ones above):&lt;/p&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix1-sm-1.gif'
onClick="showImgPick('Image number '+GetPosition(this.parentNode,this)+' in its box.')" /&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix2-sm-3.gif'
onClick="showImgPick('Image number '+GetPosition(this.parentNode,this)+' in its box.')" /&gt;
&lt;img src='https://javascriptsource.com/wp-content/uploads/2018/01/pix3-sm-1.gif'
onClick="showImgPick('Image number '+GetPosition(this.parentNode,this)+' in its box.')" /&gt;
&lt;br&gt;&lt;input id="imgNo" value="" size="30em"&gt;
&lt;/div&gt;
// end of Original version
--&gt;

&lt;fieldset id='fs3'&gt; &lt;legend&gt;Table positions&lt;/legend&gt;
&lt;p&gt;Click on a table body cell below:&lt;/p&gt;
&lt;table&gt;
&lt;caption&gt; Table &lt;/caption&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt; Column 1 &lt;/th&gt; &lt;th&gt; Column 2 &lt;/th&gt; &lt;th&gt; Column 3 &lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt; R1:C1 &lt;/td&gt; &lt;td&gt; R1:C2 &lt;/td&gt; &lt;td&gt; R1:C3 &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; R2:C1 &lt;/td&gt; &lt;td&gt; R2:C2 &lt;/td&gt; &lt;td&gt; R2:C3 &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt; R3:C1 &lt;/td&gt; &lt;td&gt; R3:C2 &lt;/td&gt; &lt;td&gt; R3:C3 &lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;input id="cellNo" value="" size="40em"&gt;

&lt;script&gt;
const doc = (IDS) =&gt; document.getElementById(IDS);

function showListPick(info) {
const str = 'Item '+GetPosition(info.parentNode,info);
doc('lstNo').value = str;
}
function showImagePick(info) {
const str = 'Image number '+GetPosition(info.parentNode,info);
doc('imgNo').value = str;
}

// Original version
// function showLstPick(info) { doc('lstNo').value = info; }
// function showImgPick(info) { doc('imgNo').value = info; }

/*
Syntax: GetPosition(main,spec)

Arguments:
main: the containing element to search
spec: the element whose position to return

Returns: The position of the given element within the given container,
relative to other elements of the same type
(0=first, -1=spec not found in main).
*/

function GetPosition(main,spec) {
items=main.getElementsByTagName(spec.tagName);
found=0;
for (p=0; p&lt;items.length; p++) {
if (items[p]==spec) { found=1; break; }
}
if (found) { return p; } else { return -1; }
}


function showPad(ndx, info) { // just some function to do for testing
var c = info.textContent || info.innerHTML;
doc('cellNo').value = 'Position '+ndx+' : '+ c;
}

function tblHandlers(clickTag){
// convert collection to array, then map each element to an event function
// var links = Array.prototype.slice.call( document.querySelectorAll(clickTag), 0 );
var links = [...document.querySelectorAll(clickTag)]; // newer method
links.map(function mapper(elm, index){
elm.addEventListener(
"click",
function clicker(e){ showPad(index, this); }, // end clicker(e) function
// function clicker(e){ doc('cellNo').value = 'Index: '+index; }, // end clicker(e) function
false
); //end addEventListener
}); //end map() function
}
tblHandlers('td')
tblHandlers('th')

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@codyhillauthorSep 14.2019 — @JMRKER#1608739 Yeah, not what I needed. What I am trying to do is when the user clicks on a dot, the specific section comes into view. Like carousels dots.

Here is the project: https://codepen.io/raul-rogojan/pen/KKPBpXJ?editors=0010
Copy linkTweet thisAlerts:
@codyhillauthorSep 14.2019 — @JMRKER#1608739 The logic I had was to get the index of the clicked dot. Then make the counter = to that index so the scrollIntoView will scroll to that specific section because of the counter is the number of the clicked dot index.
Copy linkTweet thisAlerts:
@JMRKERSep 14.2019 — Pardon my ignorance, but where is the "dot" to click on?

Also, cannot find the scroll logic for a specific index selection (?)

( You have too much code for me to analyze at one time :) )
Copy linkTweet thisAlerts:
@codyhillauthorSep 14.2019 — @JMRKER#1608742 No problem. I said in the first post that the dots are visible only for screen size > 1024px and also I said that dots are not really dots anymore because I changed the styling a bit. I also said that I have left a comment so you can see the code. The comment is /* --------The code I need help with ----------*/. In the comment there are 2 codes that I was changing around trying to make it work.

I don't know what you are referring to "cannot find the scroll logic for a specific index selection". I think that's the logic I am trying to add. I want to make the counter equal to the index number of the clicked dot so the scrollIntoView function will scroll to the corresponding section.

Here is the logic for the button
<i>
</i>nextBtn.addEventListener("click", e =&gt; {
if (counter === sections.length - 1) return;

counter++;

sections.forEach((section, index) =&gt; {
if (counter === index) {
toggleText(index, "show");
updateDot(index, "activeDot");
section.scrollIntoView({ behavior: "smooth" });
}
});
});


And here is the logic for the scroll
<i>
</i>window.addEventListener("wheel", e =&gt; {
const delta = e.wheelDelta;

if (delta &lt; 1) {
nextBtn.click();
} else {
prevBtn.click();
}
});
Copy linkTweet thisAlerts:
@daveyerwinSep 14.2019 — @RaulRogojan#1608738

<div>1</div>

<div>2</div>

<div>3</div>

<script>

divArray = document.querySelectorAll('div');

divArray.forEach((currenr,index)=>alert(index));

</script>
Copy linkTweet thisAlerts:
@JMRKERSep 15.2019 — I liked 'DaveyErwin's example and expanded it to demo your scroll index requirement (I think ???)
<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/&gt;
&lt;title&gt; Element Index Test Page &lt;/title&gt;
&lt;!-- For: https://www.webdeveloper.com/d/385790-how-to-get-the-index-of-e-target/6 --&gt;

&lt;style&gt;
ul { list-style-type: none; }
li { display: inline-block; } /* default is vertical display */
li { height: 0.6em; width: 3em; margin: 0.5em; background: lime; border: 1px solid black; }
li:hover { cursor: pointer; }
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;ul id="scrollIndex"&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;li&gt;&amp;nbsp;&lt;/li&gt;
&lt;/ul&gt;
Element Index: &lt;input id="demo" value=""&gt;

&lt;script&gt;
console.clear();
function init() {
divArray = document.querySelectorAll('#scrollIndex li');
divArray.forEach(
(el,ndx) =&gt; el.addEventListener( // substitute your own Fat-Arrow =&gt; function actions
'click',
() =&gt; { console.log(ndx); document.getElementById('demo').value=ndx; } ) );

/* following also works as alternative to above
for ( const [ndx,el] of divArray.entries()) { // alert(ndx+'t'+el.innerHTML);
el.addEventListener( // substitute your own Fat-Arrow =&gt; function actions
'click',
() =&gt; { console.log(ndx); document.getElementById('demo').value=ndx; } );
}
/* end */
} init();
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Copy linkTweet thisAlerts:
@codyhillauthorSep 15.2019 — @DaveyErwin#1608744 Hi! Thx! It works but I give me all the indexes 1 after another. It gives me

1

2

3

I was wan to get only the index of the clicked dot. Maybe I wrrite it wrong. Here is the code
<i>
</i>dots.forEach(dot =&gt; {
dot.addEventListener("click", e =&gt; {
dots.forEach((current, index) =&gt; {
console.log(index);
});
});
});
Copy linkTweet thisAlerts:
@codyhillauthorSep 15.2019 — @DaveyErwin#1608744 @JMRKER#1608745 Nvm guys. Thx for your help. I figure it out. I did it like this
<i>
</i>const navDots = document.querySelector(".nav-dots");
const dots = Array.from(navDots.children);

navDots.addEventListener("click", e =&gt; {
const clickedDot = e.target.closest("button");
const dotIndex = dots.findIndex(dot =&gt; dot === clickedDot);

counter = dotIndex;

sections.forEach((section, index) =&gt; {
if (counter === index) {
toggleText(index, "show");
updateDot(index, "activeDot");
section.scrollIntoView({ behavior: "smooth" });
}
});
});
Copy linkTweet thisAlerts:
@JMRKERSep 15.2019 — Where is your final code? I would like to see your design logic in action for this project.
Copy linkTweet thisAlerts:
@codyhillauthorSep 15.2019 — @JMRKER#1608760 [Here](https://codepen.io/raul-rogojan/pen/KKPBpXJ?editors=1100). This is just a code pen. I was not able to add the img. I am still working on it and I have some bugs now.
Copy linkTweet thisAlerts:
@JMRKERSep 15.2019 — @RaulRogojan#1608762

OK, let us know when it's ready.
×

Success!

Help @codyhill spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...