I'm trying to get the index of clicked element. This works fine so far.
Problem is that you can hide elements. If an element is hidden I don't want it to be "counted" in the index.
If you have a look at the fiddle and all boxes are orange the index is how it should be. If you click on Click me to hide some divs -- they don't get removed, in reality they get a display:none; here they just get another color to give you an idea -- they also get the class hidden so now I don't want the index to index them. But if I click on Div 2 I would like the index to show 1
I've tried with $('div').not('hidden') fiddle here -> http://jsfiddle.net/rva54sy3/2/
<script>
(function($){
var indexBoxes = function(e) {
$element = $(this);
var index = $element.not('.hidden').index();
$( "h3.txt" ).text( "That was div index #" + index );
}
$(document).on( 'click', '.getIndex', indexBoxes);
})(jQuery);
$('.hide-some-divs').on('click',function(){
$('.hide').addClass('hidden').closest('.wrap').addClass('hidden');
});
</script>
<h3 class="txt">Click a div!</h3>
<div class="wrap clearfix">
<div class="getIndex">Div 0</div>
<div class="getIndex hide">Div 1</div>
<div class="getIndex">Div 2</div>
<div class="getIndex hide">Div 3</div>
<div class="getIndex">Div 4</div>
<div class="getIndex hide">Div 5</div>
</div>
<div class="hide-some-divs">Click me to hide some divs</div>
and if you like some styling:
<style>
.getIndex {
width:100px;
height:100px;
margin:5px;
background-color:orange;
float:left;
}
.wrap.hidden > div.hide {
background-color:#fafafa;
}
.hide-some-divs {
background-color:#afafff;
padding:10px;cursor:pointer;
margin:20px auto;
width:250px;
text-transform:uppercase;
text-align:center;
}
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clearfix { display: inline-block; }
</style>
Thanks for advices
You can get the index like this way
(function($) {
var indexBoxes = function(e) {
var index = $(".getIndex").not('.hidden').index(this);
$("h3.txt").text("That was div index #" + index);
}
$(document).on('click', '.getIndex', indexBoxes);
})(jQuery);
This will the index of given element corresponding to your selected list(not related to the immediate parent). Here the selected element list is .getIndex class divs which doesnt have the class name .hidden
Fiddle
You can use $.inArray() to get the index of clicked element from visible elements.
(function($){
var indexBoxes = function(e) {
$element = $(this);
var index = ($.inArray((this),$(".getIndex").not(".hidden")));
$( "h3.txt" ).text( "That was div index #" + index );
}
$(document).on( 'click', '.getIndex', indexBoxes);
})(jQuery);
Here's a link to fiddle!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With