I am trying to make portfolio filter with js (without plugins). So far I created navigation
<div class="filter-nav">
<div class="nav-wrap">
<button class="btn fil-cat active" href="" data-rel="kuche">
<span class="ico ico-big"><img src="/assets/images/ico-kueche.svg" alt="Kueche"></span>
<span>Kuche</span>
</button>
<button class="btn fil-cat" data-rel="bade">
<span class="ico ico-big"><img src="/assets/images/ico-baeder.svg" alt="Baeder"></span>
<span>Bade</span>
</button>
<button class="btn fil-cat" data-rel="mobel">
<span class="ico ico-big"><img src="/assets/images/ico-moebel.svg" alt="Moebel"></span>
<span>Mobel</span>
</button>
<button class="btn fil-cat" data-rel="schreinerei">
<span class="ico ico-big"><img src="/assets/images/ico-kueche.svg" alt="Kueche"></span>
<span>Schreinerei</span>
</button>
<button class="btn fil-cat" data-rel="acrylstein">
<span class="ico ico-big"><img src="/assets/images/ico-baeder.svg" alt="Baeder"></span>
<span>Acrylstein</span>
</button>
<button class="btn fil-cat" data-rel="objekte">
<span class="ico ico-big"><img src="/assets/images/ico-moebel.svg" alt="Moebel"></span>
<span>Objekte</span>
</button>
</div>
</div>
with data attribute,
and rest of the code
<div id="inspiration" class="row in-wrap">
<div class="tile scale-anm kuche col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<div class="tile scale-anm bade col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<div class="tile scale-anm kuche col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<div class="tile scale-anm bade col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<div class="tile scale-anm kuche col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
<div class="tile scale-anm bade col-lg-6">
<img class="lazyload" data-srcset="../../assets/images/sample/inspiration.png," src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==">
</div>
</div>
so with data atribute I chose which one will be selected with this JS code
function filterInspiration() {
var selectedClass = "";
$('.fil-cat').click(function(){
selectedClass = $(this).attr("data-rel");
$("#inspiration").fadeTo(100, 0.1);
$("#inspiration div").not("."+selectedClass).fadeOut().removeClass('scale-anm');
setTimeout(function() {
$("."+selectedClass).fadeIn().addClass('scale-anm');
$("#inspiration").fadeTo(300, 1);
}, 300);
});
};
filterInspiration();
The part that I am stacked is, how can I add class active for example to button that I clicked, and then when I click on another button in filter navigation, then to remove on previous and add to another?
Thanks
You can use jquery function to add and remove class i.e., addClass & removeClass
First remove class active from all elements
Add active to the this (current element)
$('.fil-cat').click(function(e) {
$('.fil-cat').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="filter-nav">
<div class="nav-wrap">
<button class="btn fil-cat" href="" data-rel="kuche">
<span class="ico ico-big"><img src="/assets/images/ico-kueche.svg" alt="Kueche"></span>
<span>Kuche</span>
</button>
<button class="btn fil-cat" data-rel="bade">
<span class="ico ico-big"><img src="/assets/images/ico-baeder.svg" alt="Baeder"></span>
<span>Bade</span>
</button>
<button class="btn fil-cat" data-rel="mobel">
<span class="ico ico-big"><img src="/assets/images/ico-moebel.svg" alt="Moebel"></span>
<span>Mobel</span>
</button>
<button class="btn fil-cat" data-rel="schreinerei">
<span class="ico ico-big"><img src="/assets/images/ico-kueche.svg" alt="Kueche"></span>
<span>Schreinerei</span>
</button>
<button class="btn fil-cat" data-rel="acrylstein">
<span class="ico ico-big"><img src="/assets/images/ico-baeder.svg" alt="Baeder"></span>
<span>Acrylstein</span>
</button>
<button class="btn fil-cat" data-rel="objekte">
<span class="ico ico-big"><img src="/assets/images/ico-moebel.svg" alt="Moebel"></span>
<span>Objekte</span>
</button>
</div>
</div>
Here is a small proof of concept for the functionality you're looking for.
// Get the container with the buttons...
var container = document.getElementById('button-container');
// and add a click event listener.
container.addEventListener('click', event => {
// Find the item that has the active class...
var activeItem = container.querySelector('.active');
// when such an item exists, remove the active class from the element.
if (activeItem !== null) {
activeItem.classList.remove('active');
}
// When the clicked element is the same as the element that was active, leave. When an active button is clicked it should become inactive.
if (event.target === activeItem) {
return;
}
// Make the clicked button the active button.
event.target.classList.add('active');
});
.active {
font-size: 2em;
}
<div id="button-container">
<button type="button">Button</button>
<button type="button">Button</button>
<button type="button">Button</button>
<button type="button">Button</button>
<button type="button">Button</button>
</div>
Related
I am trying to hide / show comment replies.
I tried a few methods but couldn't get class with dynamic ids.
My html structure is like this :
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-1" id="comment-2">
//level-2 parentOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom parentOF-2" id="comment-3">
//level-3 parentOF-2
</div>
<div class="form-group border-bottom" id="comment-4">
//level-4 doesnt have child
</div>
</div>
I tried like in the following example with different variations.
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
var commet-id = $('comment-').val();
var parentOF = $('parentOF-').val();
$(this).text() == "show replies" ? $(this).text("show replies") : $(this).text("hide replies");
$(this).closest('parentOF-').nextUntil('parentOF-').slideToggle();
});
But couldn't make it work. Thanks for any help.
You could Hide At comment div's all class that contains parentOf- class ,
$("div[class*='parentOF-']").hide();
then in each button attach event that show child comment on click , otherwise hide child comment and all it's children using recuresive function described in the snippet :
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
Here a working snippet as I understand :
$(function($) {
$("div[class*='parentOF-']").hide();
$(document).on('click', '.show_reply', function(e) {
e.preventDefault();
let id = $(this).attr("id");
if( $(this).text() == "show replies" ) {
$(this).text("hide replies")
let $childComment = $(`.parentOF-${id}`)
$childComment.slideDown();
} else if($(this).text() === "hide replies") {
hideRecurssive(id);
$(this).text("show replies")
}
});
});
function hideRecurssive(id) {
let $child = $(`.parentOF-${id}`);
if($child.length>0) {
var newId = $child.attr("id")
// get last char that refer to child comment
newId = newId.charAt(newId.length - 1);
$child.slideUp();
var btn = $child.find(".show_reply");
if(btn.length) btn.text("show replies");
hideRecurssive(newId);
};
}
.hide {
color: red;
}
.unhide {
color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<div id="display_comment" class="col-12">
<div class="form-group border-bottom " id="comment-6">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri, yabancı dili İnternet&#39;teki içerik deryasını tam olarak anlamak için yeterli olmayan kullanıcılar tarafından tercih ediliyor. Bununla birlikte Google Çeviri, her zaman mükemmel t</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:38
<button type="button" class="btn btn-primary btn-xs reply" id="6">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="6" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-6" id="comment-7">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Translate aracı halihazırda 100&#39;den fazla dil arasında tercüme yapıyor.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:23:56
<button type="button" class="btn btn-primary btn-xs reply" id="7">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="7" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-7" id="comment-8">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Translate çeviriler için yakın zamana kadar Avrupa Parlamentosu ve Birleşmiş Milletler gibi büyük kuruluşların verilerini kullanıyordu. Çeviriler ayrıca sözlük bilgileri ve kullanıcılar tarafın</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:19
<button type="button" class="btn btn-primary btn-xs reply" id="8">Reply <i class="fas fa-share" aria-hidden="true"></i></button> <button id="8" type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
</div>
</div>
<div class="form-group border-bottom parentOF-8" id="comment-11">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">rew rew ew wre</div>
</div>
<div class="col-12 sttime">2021-01-09 18:10:46
<button type="button" class="btn btn-primary btn-xs reply" id="11">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
<div class="form-group border-bottom " id="comment-9">
<div class="row">
<div class="col-12"><b>Netmaster</b> said!</div>
<div class="row">
<div class="col-2 stimg">
<picture>
<source type="image/webp" srcset="uploads/images/undefined.webp">
<img src="uploads/images/undefined.jpg" alt="netmaster" class="img-fluid">
</picture>
</div>
<div class="col-10 sttext">Google Çeviri nasıl kullanılır? Google Translate anlaşılır bir arayüze sahip ancak keşfedilecek birçok özelliği var.</div>
</div>
<div class="col-12 sttime">2021-01-09 02:24:43
<button type="button" class="btn btn-primary btn-xs reply" id="9">Reply <i class="fas fa-share" aria-hidden="true"></i></button>
</div>
</div>
</div>
</div>
Updated as per request. This will allow you to show nested comments and hide them. If you hide a parent comment then all nested comments will be hidden.
N.B. I changed your parentOF- to childOF- because it didn't make sense. You can just change all incidences of the class name in the code below if you'd like to keep it.
All the code is fully commented.
// Add dynamic click event listener
$(document).on('click', '.show_reply', function(e) {
// Toggle button text
if ($(this).text() == "show replies") {
$(this).text("hide replies");
} else {
$(this).text("show replies");
}
// Get comment-id from parent element
commentID = $(this).parent().attr("id");
// Just get id
commentID = commentID.replace("comment-", "");
// Store element
el = $(".childOF-" + commentID);
// Check if element is visible
if (el.is(':visible')) {
// Check for nested comments if hiding
hideNested(commentID);
// Hide element
el.slideUp();
} else {
// Show element
el.slideDown();
}
});
function hideNested(nestedID) {
// Find element that is child of the one passed
nested = $(".childOF-" + nestedID)
// Check if nested comment exists
if (nested.length == 0) {
// Exit function if it does not
return;
}
// Hide comment
nested.slideUp();
// Update button text
nested.find("button.show_reply").text("show replies");
// Check for further nested comments
hideNested(nested.attr("id").replace("comment-", ""));
}
div[class^='childOF'],
div[class*=' childOF'] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display-comments">
<div class="form-group border-bottom" id="comment-1">
//level - 1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
<div class="form-group border-bottom childOF-1" id="comment-2">
//level-2 childOF-1
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-2" id="comment-3">
//level-3 childOF-2
<button type="button" class="btn btn-primary btn-xs show_reply">show replies</button>
</div>
<div class="form-group border-bottom childOF-3" id="comment-4">
//level-4 childOF-3
</div>
</div>
<div class="form-group border-bottom" id="comment-5">
//level-5 doesnt have child
</div>
</div>
I have a Div structure and when the div is clicked I want a link to open in a new tab. But there is a child item inside the div which has a function of copying the code. When this child item is clicked, it should not open the link in new tab.
This is my HTML structure:
$(".nuget").on('click', ':not(.copy-nuget-section)', function (e) {
window.open('http://google.pl', '_blank')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-item nuget">
<div class="product-image">
<img class="img-responsive add-shadow" alt="" src="/img/nuget-logo.png">
</div>
<div class="product-info">
<h3>Install with <span>NuGet</span></h3>
</div>
<div class="copy-nuget-section" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Click to copy">
<div class="copy-nuget-row">
<pre class="install-script">Install-Package</pre>
<div class="copy-button">
<button class="btn btn-default copy-nuget-script" type="button" data-toggle="popover" data-placement="bottom" data-content="Copied." aria-label="Copy the Package Manager command" data-original-title="" title="">
<span class="ms-Icon ms-Icon--Copy"></span>
</button>
</div>
</div>
</div>
<div class="nuget-link">nuget.org/packages/</div>
</div>
Check if the target is .copy-nuget-section or any of it's children using closest()
$(".nuget").on('click', function(e) {
if (!$(e.target).closest('.copy-nuget-section').length) {
window.open('http://google.pl', '_blank')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-item nuget">
<div class="product-image">
<img class="img-responsive add-shadow" alt="" src="/img/nuget-logo.png">
</div>
<div class="product-info">
<h3>Install with <span>NuGet</span></h3>
</div>
<div class="copy-nuget-section" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Click to copy">
<div class="copy-nuget-row">
<pre class="install-script">Install-Package</pre>
<div class="copy-button">
<button class="btn btn-default copy-nuget-script" type="button" data-toggle="popover" data-placement="bottom" data-content="Copied." aria-label="Copy the Package Manager command" data-original-title="" title="">
<span class="ms-Icon ms-Icon--Copy"></span>
</button>
</div>
</div>
</div>
<div class="nuget-link">nuget.org/packages/</div>
</div>
You can use the concept of event bubbling to stop the propagation of click event from child to parent like this.
$(".copy-nuget-section").on('click', function (e) {
// code for the copy functionality that you want to implement
e.stopPropagation()
});
$(".nuget").on('click', function (e) {
window.open('http://google.pl', '_blank')
});
enter code here
classesFilterWerke = [
'skulptur',
'malerei',
'druck',
'neueMedien',
'sozialkritischs',
'performance',
'installation',
'kunstImÖffentlichenRaum'
];
for( var i = 0; i < classesFilterWerke.length; i++ ) {
iNthChild = i+2
$('.werke-filter button:nth-child('+ iNthChild +')').click(function(){
$('.'+ classesFilterWerke[i] +'').toggle();
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="werke-filter filter-wrapper">
<p class="float-left">Filter:</p>
<button class="active btn btn-primary-outline">Skulptur</button>
<button class="active btn btn-primary-outline">Malerei</button>
<button class="btn btn-primary-outline">Druck</button>
<button class="btn btn-primary-outline">Neue Medien</button>
<button class="btn btn-primary-outline">Sozialkritisches</button>
<button class="btn btn-primary-outline">Performance</button>
<button class="btn btn-primary-outline">Installation</button>
<button class="btn btn-primary-outline">Kunst im öffentlichen Raum</button>
</div>
<a href="werk-baldachin.php?id=8" class="karte skulptur" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-longboard.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Longboard</h4>
<h5>Skulptur</h5>
</a>
<a href="werk-baldachin.php" class="karte druck" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-schale.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Keramikton Arbeiten</h4>
<h5>Skulptur</h5>
</a>
<a href="werk-baldachin.php" class="karte malerei" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-stehleuchte.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Stehleuchte</h4>
<h5>Skulptur</h5>
</a>
I want to make a filter which toggles elements with a certain class. My problem now is that if I use the jQuery .click Event Listener inside a while loop it doesn't work. If I get the jQuery statement outside of the while loop it works.
NOTE: I haven't used the i variable and the classesFilterWerke (Array) inside the loop because it doesn't work even without.
Relying on index is not the best thing. Your code already had things out of order so it would have a bug. So if you add an attribute we can simplify this code to just select that element.
I am not sure the end goal so I am just toggling a class to show it working.
$('.werke-filter').on("click", "button", function () {
var button = $(this)
var toggles = button.data("toggles")
button.toggleClass("selected")
$(toggles).toggleClass("selected")
})
.selected {
background-color: yellow;
}
.karte {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="werke-filter filter-wrapper">
<p class="float-left">Filter:</p>
<button class="active btn btn-primary-outline" data-toggles=".karte.skulptur">Skulptur</button>
<button class="active btn btn-primary-outline" data-toggles=".karte.malerei">Malerei</button>
<button class="btn btn-primary-outline" data-toggles=".karte.druck">Druck</button>
</div>
<a href="werk-baldachin.php?id=8" class="karte skulptur" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-longboard.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Longboard</h4>
<h5>Skulptur</h5>
</a>
<a href="werk-baldachin.php" class="karte druck" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-schale.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Keramikton Arbeiten</h4>
<h5>Skulptur</h5>
</a>
<a href="werk-baldachin.php" class="karte malerei" data-aos="fade-up">
<div class="karte-img">
<img src="../assets/img/werke/thumb-skulptur-stehleuchte.jpg" alt="">
</div>
<div class="stroke-bottom"></div>
<h4>Stehleuchte</h4>
<h5>Skulptur</h5>
</a>
I've got a page with multiple div elements of class 'container', ie:
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> 123456789 </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard </button>
</div>
</div>
How can I select all buttons of class 'delete', but only if the a element had origin="internal"?
The common ancestor of both elements is the div of class "container".
Besides, how can I programmatically click on all those buttons on page load?
You can select all the buttons with class="delete" and then you can use an if else statement. For example:
$('.delete').on('click',function(){
if($(this).parent().data('origin') == 'internal'){
//do something
}else{
//do something else
}
})
Filter and map all containers:
const result = Array.from(document.querySelectorAll(".container"))
.filter(c => c.querySelector("a[origin=internal]"))
.map(c => c.querySelector("button.delete"));
console.log(result);
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> A </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard A </button>
</div>
</div>
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="external"> B </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard B </button>
</div>
</div>
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> C </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard C </button>
</div>
</div>
(Furthermore, i believe that jQuery should never be used.)
<div class="panel">
<div class="panel-heading item-name">T-shirt1</div>
<div class="panel-body"><img src="img/shirt1.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$15.32</span></h5>
<h4>$17.56</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>
<div class="panel">
<div class="panel-heading item-name">T-shirt2</div>
<div class="panel-body"><img src="img/shirt2.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$21.67</span></h5>
<h4>$23.15</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>
<div class="panel">
<div class="panel-heading item-name">T-shirt3</div>
<div class="panel-body"><img src="img/shirt3.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$16.69</span></h5>
<h4>$16.80</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>
What I really want is to retrieve the value of each item-name when I click on the Add to cart button. If I click on the first button, I should get T-shirt1, second button should alert T-shirt2, third button => T-shirt3.
Here is my jQuery script.
<script>
$('.add-to-cart').click(function() {
var itemName = $('.item-name', this).text();
alert(itemName);
});
</script>
You can try this:
$('.add-to-cart').click(function() {
var itemName = $(this).closest('.panel').find('.item-name').text();
alert(itemName);
});
Usage of the closest method: closest
Go from clicked button up in parents chain until you find .panel and then down in children tree until you find .item.name:
$('.add-to-cart').click(function() {
var itemName = $(this).parents('.panel').children('.item-name').first().text();
alert(itemName);
});