index of nested div with click event with jquery? - javascript

I have a click event that I'm using trying to get the index of the outermost parent div but can't seem to return it.
Here is the list of several divs:
<div class="owl-item">
<div class="icon-holder-selection" id="sel11">
<div class="thumbnail" id="cur11">
<img src="images/icons/11.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="11"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
<div class="owl-item">
<div class="icon-holder-selection" id="sel12">
<div class="thumbnail" id="cur12">
<img src="images/icons/12.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="12"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
<div class="owl-item">
<div class="icon-holder-selection" id="sel13">
<div class="thumbnail" id="cur13">
<img src="images/icons/13.jpg">
<div class="icon-action">
<span class="glyphicon glyphicon-remove remove-selection" id="13"></span>
<span class="icon-content">Remove</span>
</div>
</div>
</div>
</div>
My click event looks like this:
$(document).on("click", ".remove-selection", function(e) {
e.preventDefault ();
//var index = $(this).index();
var parent = $(this).closest('div');
var index = $(".owl-item").index(parent);
console.log("INDEX: " + index);
});
Any idea what I'm missing?

You need to provide a class name .owl-item for the div in .closest(), otherwise it will just return a direct parent of your span element.
Working demo: http://jsfiddle.net/1t6xgbth/
$(document).on("click", ".remove-selection", function(e) {
e.preventDefault ();
//var index = $(this).index();
var parent = $(this).closest('div.owl-item');
var index = $(".owl-item").index(parent);
alert(index);
console.log("INDEX: " + index);
});

Using delegateTarget is easier and simpler by using the owl-item selector instead of document:
$('.owl-item').on("click", ".remove-selection", function(e) {
e.preventDefault ();
console.log($(e.delegateTarget).index());
});
Another fiddle

Related

jQuery callback function to check number of child elements on element click

I have a set of "div" whose children count I want to check when a user fadeOut images under that div block, if the all childrens have be closed out i want to call the function: kind of like:
edited: the current code always alerts YES whenever the div is faded,
how do i destroy the DOM entirely without having to use :visible
filter. getting rid of the entire card class after fading out
considering the HTML:
<div class='scrolling-wrapper'>
<div class='card'>
<div class='panel panel-primary'>
<div class='panel-body'>
<div class='img-wrap'>
<span class='close-x'> × </span>
<img width='100%' id='3' class='' src='resizer/resizer.php?file=profiles/images/default_cover.jpg&width=700&height=400&action=resize&watermark=bridgoo&watermark_pos=tl&color=255,255,255&quality=100' />
</div>
<div class='title h5'>
<span class='user-popover'>
<a href='/groupstomason/'><b>tomason</b></a>
</span>
<br/>
<small class='small-text'>for max tomason
</small>
</div>
</div>
<div class='panel-heading'>
<button class='btn btn-primary'> <span class='fa fa-plus-circle fa-fw'> </span>Join </button>
</div>
</div>
<div class='card-group-holder' style='width:250px; background-color:inherit;'>
</div>
<div class="card"> another card</div>
<div class="card"> another card</div>
<div class="card"> another card</div>
</div>
and the jquery below:
$('.img-wrap .close-x').on('click', function() {
var card = $(this).closest('.card');
card.fadeOut('slow', function() {
var cardWrapper = $(this).closest('.card').closest('scrolling-wrapper');
var cardcount = cardWrapper.children('.card');
if (cardcount.length < 1) alert('yes');
});
});
when the <span class = 'close-x'> × </span> is clicked the
entire <div class='card'> is fadedOut, then on fadeout, if no more
cards exist or the last cards have been faded, then alert('yes');
Assuming that multiple .card elements are nested in the same parent, you can check if all the siblings have faded out.
In your original markup, you have an unclosed </div>, which causes the .card elements not to be siblings of each other, I believe this is a typo on your part, since it is the most parsimonious explanation.
Since .fadeOut() hides the element, you can simply check if the filtered set of :visible returns a length of 1 or more:
$('.img-wrap .close-x').on('click', function() {
var card = $(this).closest('.card');
card.fadeOut('slow', function() {
var cardWrapper = $(this).closest('.scrolling-wrapper');
var cardcount = cardWrapper.children('.card');
if (cardcount.filter(':visible').length < 1) {
console.log('All cards have faded out');
}
});
});
Here is a proof-of-concept example:
$(function() {
$('.close').on('click', function() {
var card = $(this).closest('.card');
card.fadeOut('slow', function() {
// Get wrapping ancestor
var cardWrapper = $(this).closest('.scrolling-wrapper');
var cardcount = cardWrapper.children('.card');
// Filter out those that are not visible, and check for remaining visible cards
if (cardcount.filter(':visible').length < 1) {
console.log('All cards have faded out');
}
});
});
});
/* Just styles for a dummy call-to-action element in .card */
span.close {
cursor: pointer;
color: steelblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrolling-wrapper">
<div class="card">Card 1. <span class="close">Click to hide me.</span></div>
<div class="card">Card 2. <span class="close">Click to hide me.</span></div>
<div class="card">Card 3. <span class="close">Click to hide me.</span></div>
<div class="card">Card 4. <span class="close">Click to hide me.</span></div>
<div class="card">Card 5. <span class="close">Click to hide me.</span></div>
</div>
In your callback you may simply test if at least a card is visible:
if ($(this).closest('.card').siblings('.card:visible').length < 1) alert('yes');
$('.img-wrap .close-x').on('click', function () {
var card = $(this).closest('.card');
card.fadeOut('slow', function () {
if ($(this).closest('.card').siblings('.card:visible').length < 1) console.log('yes');
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class='scrolling-wrapper'>
<div class='card'>
<div class='panel panel-primary'>
<div class='panel-body'>
<div class='img-wrap'>
<span class='close-x'> × </span>
<img width='100%' id='3' class=''
src='resizer/resizer.php?file=profiles/images/default_cover.jpg&width=700&height=400&action=resize&watermark=bridgoo&watermark_pos=tl&color=255,255,255&quality=100'/>
</div>
<div class='title h5'>
<span class='user-popover'>
<a href='/groupstomason/'><b>tomason</b></a>
</span>
<br/>
<small class='small-text'>for max tomason
</small>
</div>
</div>
<div class='panel-heading'>
<button class='btn btn-primary'><span class='fa fa-plus-circle fa-fw'> </span>Join</button>
</div>
</div>
<div class='card-group-holder' style='width:250px; background-color:inherit;'>
</div>
</div>
<div class='card'>
<div class='panel panel-primary'>
<div class='panel-body'>
<div class='img-wrap'>
<span class='close-x'> × </span>
<img width='100%' id='3' class=''
src='resizer/resizer.php?file=profiles/images/default_cover.jpg&width=700&height=400&action=resize&watermark=bridgoo&watermark_pos=tl&color=255,255,255&quality=100'/>
</div>
<div class='title h5'>
<span class='user-popover'>
<a href='/groupstomason/'><b>tomason</b></a>
</span>
<br/>
<small class='small-text'>for max tomason
</small>
</div>
</div>
<div class='panel-heading'>
<button class='btn btn-primary'><span class='fa fa-plus-circle fa-fw'> </span>Join</button>
</div>
</div>
<div class='card-group-holder' style='width:250px; background-color:inherit;'>
</div>
</div>
</div>

How to set class active to div?

I have this menu in this fiddle and I want to set active div on click:
<div class="account-item">
<div class="account-heading active">
<h4 class="account-title">
2. TRANSACTION_HISTORY
</h4>
</div>
</div>
I have this script but i get selected all divs
function SetActiveDiv()
{
var element = $("a").parent().parent();
if (element.hasClass("active")) {
element.removeClass("active");
} else {
element.addClass("active");
}
}
You need to pass the clicked element reference
1.MY_TICKETS
then
function SetActiveDiv(el) {
var element = $(el).closest('.account-heading');
element.toggleClass("active");
}
Demo: Fiddle
Note: Since you are using jQuery, try to use jQuery event handlers instead of inline handlers
So
1.MY_TICKETS
then
jQuery(function ($) {
$('.account-group .account-title a').click(function () {
var $heading = $(this).closest('.account-heading').toggleClass("active");
$('.account-group .account-heading.active').not($heading).removeClass('active');
})
})
Demo: Fiddle
just make the selector to look like (double class selector):
var element = $(".account-heading.active");
You need to take a look at your code and understand what it is doing. Take the following line:
$("a").parent().parent();
What does this do? It selects every anchor, then selects the parent, then selects the parent of that parent.
Considering you're using jQuery, you can use it to bind the event handler instead of using onClick in your html (which is considering bad practice).
$('a').on('click', function() {
$('.account-heading').removeClass('active');
$(this).parent().parent().addClass('active');
});
jsFiddle: http://fiddle.jshell.net/jxmbj36s/5/
Remove all the functions in html onclick="SetActiveLink('#/*')" and then use this jQuery function so you will not be repetitive:
$(".account-group a").on("click", function(){
$(".account-group a").removeClass("active");
$(this).addClass("active");
});
See the result here:
$(".account-group a").on("click", function(){
$(".account-group a").removeClass("active");
$(this).addClass("active");
});
.active {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-2 col-md-3 left-sidebar-container">
<div class="left-sidebar">
<div class="account">
<h1>MY_ACCOUNT</h1>
<div class="account-group" id="accordion">
<div class="account-item">
<div class="account-heading">
<h4 class="account-title">
1.MY_TICKETS
</h4>
</div>
</div>
<div class="account-item">
<div class="account-heading">
<h4 class="account-title">
2. TRANSACTION_HISTORY
</h4>
</div>
</div>
<div class="account-item">
<div class="account-heading">
<h4 class="account-title">
3. PAYIN
</h4>
</div>
</div>
<div class="account-item">
<div class="account-heading">
<h4 class="account-title">
4.PAYOUT
</h4>
</div>
</div>
<div class="account-item">
<div class="account-heading active">
<h4 class="account-title has-sub">
<a data-toggle="collapse" data-parent="#accordion" href="#settings">5.SETTINGS</a>
</h4>
</div>
<div id="settings" class="account-collapse collapse in">
<div class="account-body">
PERSONAL_INFORMATION
NOTIFICATIONS
CHANGE_PASSWORD
GAME_SETTINGS
</div>
</div>
</div>
<div class="account-item">
<div class="account-heading">
<h4 class="account-title has-sub">
<a data-toggle="collapse" data-parent="#accordion" href="#promotions">6.PROMOTIONS</a>
</h4>
</div>
<div id="promotions" class="account-collapse collapse">
<div class="account-body">
BONUSES
COMPETITIONS
VOUCHER_REDEEM
</div>
</div>
</div>
<div class="account-item">
<div class="account-heading">
<h4 class="account-title">
7. SYSTEM_MESSAGES
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
I think that the following code will help you to solve this problem
function SetActiveDiv() {
var el = $("a").closest("div.account-heading")[0];
var el = $("a").parent().parent();
if ($(el).hasClass('active')) {
$(el).removeClass('active')
} else {
$(el).addClass('active')
}
}

Finding clicked item from a span using jquery

I have following HTML. I am trying to find the clicked item. For example: if I clicked on ups the o/p should be ups like that. I have written
like this but not getting what I need.This returns all text.
$('.sentiment-text .text').on('click',function(e) {
var str = $('.sentiment-text .text').find('span').text();
alert(str);
});
Here is the HTML code which I am trying.After I have written above code I am getting full text But not getting only the item I clicked
<div class="sentiment-text">
<div class="wrapper">
<div class="key"></div>
<div class="text" style="cursor: pointer;"><div class="tags alert-success">×
<span class="noun">Thumbs</span>
<span class="adverb">up</span>
<span class="verb">ups</span>
<span class="verb">down</span>
</div>
</div>
<div class="clear-sentiment"></div>
</div>
</div>
You need to use this for the context and target the span in the selector itself.
$('.sentiment-text .text span').on('click',function(e) {
var str = $(this).text();
alert(str);
});
DEMO
So rather that putting the handler on the div why not target the spans within .text and report the text
$('.text span').on('click', function(e) {
var str = $(this).text();
alert(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentiment-text">
<div class="wrapper">
<div class="key"></div>
<div class="text" style="cursor: pointer;">
<div class="tags alert-success">×
<span class="noun">Thumbs</span>
<span class="adverb">up</span>
<span class="verb">ups</span>
<span class="verb">down</span>
</div>
</div>
<div class="clear-sentiment"></div>
</div>
</div>
Use below:
$('.text span').on('click', function() {
alert($(this).text());
});
$('.sentiment-text span').on('click',function(e) {
var str = $(this).text();
alert(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentiment-text">
<div class="wrapper">
<div class="key"></div>
<div class="text" style="cursor: pointer;"><div class="tags alert-success">×
<span class="noun">Thumbs</span>
<span class="adverb">up</span>
<span class="verb">ups</span>
<span class="verb">down</span>
</div>
</div>
<div class="clear-sentiment"></div>
</div>
</div>
try this :
$('.sentiment-text .text').find('span').on('click',function(e) {
var str = $(this).text();
alert(str);
});
I have solved this way
$('.sentiment-text span').live('click',function(e) {
var str = $(this).text();
alert(str);
});
Note that changed 'on' to 'live'. I know it is deprecated form Jquery 1.7.But no other way for me.

How to get each element and assign them an inline style contained inside the child

I've been looking for an elegant solution for a day now and I am pretty new to jQuery.
I would like to get each .figure and assign them an inline style where the value is contained inside the child element via a custom data- attribute :
<div>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-01-thumbnail.png" src="images-01.png" />
</div>
<div class="content">
<h3>Sale</h3>
<h4>Discover our latest styles</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-02-thumbnail.png" src="images-02.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
<a href="#">
<div class="figure">
<img class="thumbnail" data-thumbnail="images-03-thumbnail.png" src="images-03.png" />
</div>
<div class="content">
<h3>Free Shipping</h3>
<h4>When you buy xxxxxx</h4>
</div>
</a>
</div>
In other words, the results would be :
...
<div class="figure" style="background: url(images-01-thumbnail.png);">
...
<div class="figure" style="background: url(images-02-thumbnail.png);">
...
<div class="figure" style="background: url(images-03-thumbnail.png);">
...
Also, I'm always ready something about jQuery so if you have any books about JavaScript or jQuery to suggest, that is always appreciated.
You can iterate over all .picture elements, find the image descendant and read its data attribute:
$('.figure').css('background', function() {
return 'url(' + $(this).children('img').data('thumbnail') + ')';
});
Some methods, like .css even accept functions so that you can iterate over the selected elements implicitly.
Reference: .css, .children, .data
you can iterate over each item with the class thumbnail and set the css property to the closet div.
$('.thumbnail').each(function() {
var $this = $(this),
$background = $this.data('thumbnail');
$this.closest('.figure').css({background : $background} )
});
This should work
$("[data-thumbnail]").each(function ()
{
var $this = $(this), url = $this.data("thumbnail");
$this.parents(".figure").css("background-image", 'url("' + url + '")');
});
How about this (Working code example: http://jsfiddle.net/jpbH2/2/):
var pathToImages = "/";
$(".figure img").each(function(){
$(this).parent().css({"background": "url(" + pathToImages + $(this).data('thumbnail') +")"})
});
Edit
I actually didn't notice the data-thumbnail. Edited my answer above

Toggle Javascript outside of parent

I have issues when trying to place an event to toggle a div using an element outside of the parent container.
I trying to target the same behavior from outside of the parent elements using a span tag.
Any help would be grateful.
HTML:
<div class='toggle_parent'>
<div class='toggleHolder'>
<span class='toggler'>Open</span>
<span class='toggler' style='display:none;'>Close</span>
</div>
<div class='toggled_content' style='display:none;width:100%;height:400px;'>
<h2>Hello This Is My Content Right Here</h2>
<span class='toggler btn btn-large'>Close</span>
</div>
</div>
<!-- I need this element to trigger from outside -->
<span class="toggler btn btn-large btn-info">Gain Early Access</span>
Javascript:
$('.toggler').live('click',function(){
/* $(this).parent().children().toggle(); //swaps the display:none between the two spans */
$(this).parent().parent().find('.toggled_content').slideToggle(); //swap the display of the main content with slide action
});
Amended your example to suit the purpose.
<div id="container">
<div>
<div>
<span class='open'>Open</span>
<span class='close' style='display:none;'>Close</span>
</div>
<div class='content' style='display:none;width:100%;height:400px;'>
<h2>Hello This Is My Content Right Here</h2>
<span class='close'>Close</span>
</div>
</div>
<!-- I need this element to trigger from outside -->
<span class="toggle">Gain Early Access</span>
</div>
$(".toggle").click( function( ) {
$(".content").slideToggle();
});
$(".open").click( function( ) {
$(".content").slideDown();
});
$(".close").click( function( ) {
$(".content").slideUp();
});
Just use a global parent div.
<div id="container">
<div class='toggle_parent'>
<div class='toggleHolder'>
<span class='toggler'>Open</span>
<span class='toggler' style='display:none;'>Close</span>
</div>
<div class='toggled_content' style='display:none;width:100%;height:400px;'>
<h2>Hello This Is My Content Right Here</h2>
<span class='toggler btn btn-large'>Close</span>
</div>
</div>
<!-- I need this element to trigger from outside -->
<span class="toggler btn btn-large btn-info">Gain Early Access</span>
</div>
And you can just do this :
var container = $('#container');
container.on('click', '.toggler', function() {
container.find('.toggleHolder .toggler').toggle();
container.find('.toggle_content').slideToggle();
});
By the way, if you use jQuery 1.7 or more, live is deprecated. See http://api.jquery.com/live/

Categories

Resources