Get index of an item from a group of identical items - javascript

Say I have a group of HTML tags that are identical, e.g.:
<div id="stuff">
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
</div>
I'm attaching an onclick event to the spans like so:
$(".foo").click(function() {
// stuff
});
In my onclick event, I want to get the index of the clicked element, so for example, if I clicked the 3rd span, I want the index to be 3. How would I do that? Normally, I'd iterate over $("#stuff") and compare the items to the clicked item, but in this case, they are identical.

Get the index by using:-
Indexes are zero based relative to its siblings. SO for the 3rd element you will get the index as 2.
$(".foo").click(function() {
alert($(this).index());
}
Read about .index()
Demo

HTML
<div id="stuff">
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
</div>
Jquery
$(document).ready(function(){
$('.foo').click(function(){
var x = $(this).index();
alert(x);
});
});
working Demo http://jsfiddle.net/cse_tushar/Jj72A/

You can write it like this:
$(".foo").click(function(){
alert(jQuery.inArray(this,$(".foo")));
});

Related

How to click a button using html or java script which is declared as div

I am writing a powershell script to login to a website. I want to use the button.click functionality but I can't find the button's id. here is what I found by inspecting it.
<div tabindex="0" role="button" class="v-button v-widget default v-button-default">
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
</div>
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
<span class="v-button-caption">Login</span>
Thanks in advance
Given that you aren't sure which one is the one you want, you could just set up an event handler that will trigger for each and then interrogate it for something that can identify it.
// Get all the elements with a class of "v-button-caption" into an array
var buttons = Array.prototype.slice.call(document.querySelectorAll(".v-button-caption"));
// Loop over the array
buttons.forEach(function(btn){
// Set up a click event handler
btn.addEventListener("click", function(evt){
// Print out some identifying information about the clicked element
console.log("You clicked the element who's parent is: " + evt.target.parentElement.nodeName);
});
});
<div tabindex="0" role="button" class="v-button v-widget default v-button-default">
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
</div>
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
<span class="v-button-caption">Login</span>

AngularJS & jQuery - How to find the ID of a child div on a Click event for its parent?

I have code in HTML like:
<div id="edit" ng-click="editFunction($scope)">
<span id="1">
click1
</span>
<span id="2">
click2
</span>
<span id="3">
click3
</span>
<span id="4">
click4
</span>
....
</div>
In controller.js:
myDIV.controller('control',function($scope){
$scope.editFunction($event){
alert($event.target.id);
}
});
When a user clicks on the div tag, he should click on any of the span tags. Using the code we are able to get the div id.
However, I need to know which span is clicked. Meaning, the ID of that span.
By sending $index, you get the number of the element in the current repeat.
So instead of trying to send an event, and then understand from that what span was clicked, just use the tools that angular gives you out of the box.
HTML
<div id="edit">
<span ng-repeat="click in clicks" ng-click="editFunction($index)">
{{ click }}
</span>
</div>
And then in your controller:
myDIV.controller('control',function($scope){
$scope.clicks = [1, 2, 3, 4]; // Fill the array with real data.
$scope.editFunction(index){
alert(index);
}
});
U can use like this
<div id="edit" ng-click="editFunction($event)">
element.target.attributes.id.value

Only fire one onmouseover when hovering over multiple elements

I'd like to have basic code like the following:
<span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span>
However, I'd like to keep it from firing both of these events if both are being hovered over; e.g. if I hover over "this" it should fire only its event and alert "hello." How can I do this?
Thank you in advance!
$(".container").hover(function(){
alert($(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="container" id="hi">
Hello,
</span>
<span class="container" id="hello">
this
</span>
<span class="container" id="hi">
is a test
</span>
I am going to assume that the overlapping elements are not the same size. I.e one is bigger than the other.
HTML and inline js:
<span class="container" id="hi">
Hello,
</span>
<span class="container " id="hello">
this </span>
<script>
var hello =
document.getElementById("hello");
var this =
document.getElementById
("this");
hello.addEventListener("click
",pop("hello"));
this.addEventListener("click",pop(" hi");
function pop(string) {
window.alert(string);
}
<\script>
That being said very little is mentioned about the nature of the elements this and hello. Op plz show your CSS and update ques
Here's the relevant portion of what I ended up using. I used JQuery.
var mouseHovered = function(element) {
//get all hovered spans
var hoveredElements = $("span:hover");
//get the element with the smallest text
var smallestElement;
for(var i=0; i<hoveredElements.length; i++) if(!smallestElement || hoveredElements[i].textContent.length < smallestElement.textContent.length) smallestElement = hoveredElements[i];
//if this is the smallest text in the elements
if(element == smallestElement) {
//log the text
console.log(element.textContent);
}
}
You need to prevent Event bubbling when you hover/click on inner span.
This can be done using event.stopPropagation().
Look at two solutions provided at this JSFiddle.
Solution 1 - Use of e.stopPropagation() in the handler function innerSpan().
Solution 2 - Use of event.stopPropagation() in inline onclick event.
<span onclick="alert('Outer span');">
Outer
<span onclick="event.stopPropagation(); alert('Inner span');">
Inner
</span>
</span>

recognize which span tag triggered javascript function in div

I have a div html element that has a click event set on it inline (not the way I want to do it but legacy code). See here
<div class="myDiv" onclick="triggerJavascript();" id="myDiv">
<span id="text1">Text 1<span>
<span id="text2">Text 2<span>
<span id="text3">Text 3<span>
<span id="text4">Text 4<span>
<span id="text5">Text 5<span>
What I want to do is recognize which span tag the click event originates from test5, then dont carry out the logic in triggerJavascript function, otherwise complete logic in triggerJavascript.
How can I set this up? I am working with jquery.
You can use event.target in order to access the element. However, in order to get to this element you have to change your onclick attribute a little bit:
<div class="myDiv" onclick="triggerJavascript(event);" id="myDiv">
then you can access event in triggerJavascript:
function triggerJavascript(e){
var element = e.target;
}
See also this answer for a more detailed explanation why event is needed.
Demo ; Demo with text5 check:
<script>function triggerJavascript(e){
if(e.target.id === "text5")
alert("text 5 hit");
e.stopPropagation();
}
</script>
<div class="myDiv" onclick="triggerJavascript(event);" id="myDiv">
<span id="text1">Text 1</span> <!-- closing tags -->
<span id="text2">Text 2</span>
<span id="text3">Text 3</span>
<span id="text4">Text 4</span>
<span id="text5">Text 5</span>
</div>
You can't use onclick="triggerJavascript();", or the event target (the span which was clicked) will not be passed to the event handler.
Since you state you're using jQuery, use this:
$('#myDiv').click(function(evt) {
alert("The target is: " + evt.target.id);
});
HTML
<div class="myDiv" onclick="triggerJavascript(event);" id="myDiv">
<span id="text1">Text 1<span>
<span id="text2">Text 2<span>
<span id="text3">Text 3<span>
<span id="text4">Text 4<span>
<span id="text5">Text 5<span>
</div>
JavaScript
<script type="text/javascript">
function triggerJavascript(event) {
// event.target will catch the clicked element
if (event.target.id !== 'text5') {
// do something
}
}
</script>
DEMO
If you can't change the HTML, you could try something like this:
var triggerJavascript = (function(){
var clicked;
$("#myDiv span").click(function(e){
clicked = $(e.target).attr("id");
});
return function() {
if (clicked == "text5") {
return;
}
//do something cool...
}
})();
Although I guess, there's no guarantee that the jQuery click handler is executed before the actual triggerJavascript logic, so this might not always work correctly.

Preventing the user to click a div when its fading out

I'm trying to create a filtering system where the user can filter for answers using more than one category, but the user can't choose more than one option from each category, so upon clicking an option from any category, that category will fade out ... I have the following little problem, if the user clicks on another option from the same category while it's fading out, he will be able to choose two options from the same category ... How can I disable any click on the category when it's fading out ??
Here is the code I'm using:
HTML:
<div class="search-list" id="program-list">
<span class="search-title">Category 1</span>
<span data="program-list">Option 1</span>
<span data="program-list">Option 2</span>
<span data="program-list">Option 3</span>
<span data="program-list">Option 4</span>
<span data="program-list">Option 5</span>
<span data="program-list">Option 6</span>
</div> <!-- search-list -->
<div class="search-list" id="trainer-list">
<span class="search-title">Category 2</span>
<span data="trainer-list">Option 1</span>
<span data="trainer-list">Option 2</span>
<span data="trainer-list">Option 3</span>
<span data="trainer-list">Option 4</span>
</div> <!-- search-list -->
<div class="search-list" id="issue-date">
<span class="search-title">Category 3</span>
<span data="issue-date">Option 1</span>
<span data="issue-date">Option 2</span>
<span data="issue-date">Option 3</span>
<span data="issue-date">Option 4</span>
<span data="issue-date">Option 5</span>
<span data="issue-date">Option 6</span>
</div> <!-- search-list -->
JQuery:
$('.search-option').click(function(){
var x = $(this).html();
$('#filtered-items').append(x);
$(this).parent('.search-list').fadeTo('slow', 0);
$('#filtered-items > span').click(function(){
$('#'+$(this).attr('data')).fadeTo('slow', 100);
$(this).hide();
});
});
I tried using the following JQuery code but it didn't work:
$('.search-option').click(function(e) {
e.preventDefault();
});
Thanks in advance...
You can set an indicator in your function:
$('.search-option').click(function(){
if(indicator) {
return false
}
...
}
The indicator is something set when the fade starts and clears when it ends. It could be:
a javascript variable,
or - you can check the current opacity,
or - or you can set/clear a class name during the fade.
Simply remove the 'search-option' class from all options in a category once it is clicked.
You can set the click event to null once it has fired:
$('.search-option').click(function(){
$(this).click(null); // set click to do nothing on the clicked element
var x = $(this).html();
$('#filtered-items').append(x);
$(this).parent('.search-list').fadeTo('slow', 0);
$('#filtered-items > span').click(function(){
$('#'+$(this).attr('data')).fadeTo('slow', 100);
$(this).hide();
});
});
This will only turn off the click action on the specifically clicked element so your other filters will continue to work until each of them has been selected once. If you want to re-enable the click function after everything has happened you can save the function, disable it, then re-enable at the end as below:
$('.search-option').click(function(){
var fun = $(this).click;
$(this).click(null); // set click to do nothing on the clicked element
// OTHER CODE
$(this).click(fun);
});
Since this all hinges on the user clicking on an element with the class "search-option", just remove that class from the element and its siblings before starting the fade and then restore it with a callback after the fade runs. That way, nobody can click twice:
$('.search-option').click(function() {
var x = $(this).html();
$('#filtered-items').append(x);
$(this).parent().children().removeClass('search-option');
$(this).parent('.search-list').fadeTo('slow', 0, function() {
$(this).children().addClass('search-option');
});
});
Hey everyone ... I finally solved it, I had to change the whole structure of the function and use the methods "unbind" and "bind" ... Here is the solution if anyone is interested in it:
$('.search-option').click(work);
});
function work(){
var x = $(this).html();
$('#filtered-items').append(x);
$(this).unbind('click');
$(this).siblings('a').unbind('click');
$(this).parent('.search-list').fadeOut('slow');
$('#filtered-items > span').click(function(){
$('#'+$(this).attr('data')).fadeIn('slow');
$('#'+$(this).attr('data')).children('a').bind('click',work );
$(this).remove();
});
};
Now the user can't choose more than one option at each category ....
Try:
$('.search-option').click(function(){
var x = $(this).html();
$('#filtered-items').append(x);
// ADDED LINES
$(this).parent('.search-list').find('a').each(function(){
$(this).click(function(){return false;});
});
// END: ADDED LINES
$(this).parent('.search-list').fadeTo('slow', 0);
$('#filtered-items > span').click(function(){
$('#'+$(this).attr('data')).fadeTo('slow', 100);
$(this).hide();
});
});

Categories