I have a menu with some post categories:
<ul>
#foreach($categories->get() as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
When I click in the category, for example with id "1", through the menu it appears in the #posts div the posts that belong to the category with id "1".
Issue:
It working fine, the issue is that at first I want to have the first category with the class "active". But when another category is clicked I want to show that clicked category with the class active. But is not working like that, when the page is acessed all categories are active and also when another category is clicked all categories are active. Do you know how to correct the issue?
The #posts div shows the last posts when the page is acessed at first:
<div id="posts">
#foreach($posts as $key => $post)
<div id="post" + {{$key}}>
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
#endforeach
</div>
jQuery code:
$("a[name='category']").on('click', function(){
//tried this by given answer which not worked
var category_id = $(this).attr("id");
('.categories li').removeClass('active');
$(this).addClass('active');
//ended code
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
var newPosts = "";
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' + + '<h1>' + post.title + '</h1>';
});
$('#posts').html(newPosts);
}, error: function(error) {
console.log(error.status)
}
});
});
You need to add two line jquery code inside click event handler
$('ul li').removeClass('active');// remove active class from li
$(this).parent('li').addClass('active'); // add active class to current clicked li
Related
I'm creating a commerce site for my portfolio and I have a page with gallery of product cards that I would like to add filters for. The cards were generated dynamically using a json file.
I can figure this out using just javascript and CSS but in reviewing other sites I noticed that then you trigger their filters, parameters are appended to or removed from the url.
Here's my javascript for this page. As you can see I already use a function that takes you to an individual item by appending to the url, but I can't figure out how this is done for filters.
// ========== Load Gallery Images ========================================
$.getJSON("../../json/guitars.json", function(data) {
var guitar_data = '';
for(var i in data) {
// data
var image1 = data[i].img1
var alt = data[i].alt
var title = data[i].title // use for sort-by
var price = data[i].price
// filters
var id = data[i].product_id
var category = data[i].category
var brand = data[i].brand
var condition = data[i].condition
guitar_data += '<div class="gallery-card">'
guitar_data += `<img class="more-info img-fluid" src="../${image1}" alt="${alt}">`
guitar_data += `<h6>${title}</h6>`
guitar_data += `<p><strong>${price}</strong></p>`
guitar_data += '</div>'
}
$('#img-gallery').html(guitar_data)
})
// ========== Load Gallery Images End ====================================
$(document).ready(function() {
// ======== More Info ==================================================
$(".more-info").on("click", function(e) {
const product_id = $(e.target).attr('product_id')
$.getJSON("../../json/guitars.json", function(json) {
for(let i in json) {
if (product_id === json[i].product_id ) {
window.location.href = "./product.html?product=" + product_id
}
}
})
})
// ======== More Info End ===============================================
Here is one of my filters
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body" style="border:none;">
<ul style="list-style:none;padding-left:5px;">
<li>
<input type="checkbox" name="brand" value="fender">
<label style="padding-left:10px;" for="">Fender</label>
</li>
<li>
<input type="checkbox" name="brand" value="gibson">
<label style="padding-left:10px;" for="">Gibson</label>
</li>
<li>
<input type="checkbox" name="brand" value="gretsch">
<label style="padding-left:10px;" for="">Gretsch</label>
</li>
</ul>
</div>
</div>
I'm not asking for anyone for code, but rather direction. I'm a bit lost at the moment.
You can wrap the related html layout in a FORM with method="GET", and you call form's submit() at every filter click.
In this way every selected field would update the URL parameters i.e. querystring.
I'm trying to achieve the following:
Capture the mega menu link that's being clicked. If the link is a sub link, capture the parent link and child link as one into the Label paramater seperated with a colon.
This is the jsbin link to the HTML:
http://jsbin.com/kuliberefi/edit?html,output
I have managed to get the following code to console log the li's that I click on, but I am stuck on getting the parent link of the category. eg. When I go into the Mens section and click on shirts its meant to console log 'Mens: Shirts'.
my code:
$(".megaMenuList li").mousedown(function () {
var value = $(this).attr('href');
console.log(value);
});
Thank you to anyone that can give me some advise.
You can split the href value and take second and third item (first one will be empty). Updated bin
$(".megaMenuList a").click(function (e) {
e.preventDefault();
var value = $(this).attr( "href" );
var items = value.split("/");
console.log( items[1] + " : " + items[2] );
});
If you want the values in the URL, #gurvinder372 answer will do. If you want the actual values printed on your screen this solution will work.
$(function(){
$('.megaMenuList li a').click(function (e) {
e.preventDefault()
// get the text of the link clicked
var subcat = $(this).text();
// find the H2 that is on top of this megaMenuList
var cat = $(this).closest('.megaMenuList').find( "h2" ).text() ;
// output your cat & subcat
if( cat ){
console.log( subcat + ' : ' + cat );
} else {
console.log( subcat );
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="megaMenuList">
<ul>
<li>Shirts</li>
<li>Dresses</li>
<li>Trousers</li>
<li>Skirts</li>
<li>Socks</li>
<li>Underwear</li>
</ul>
</div>
<div class="megaMenuList">
<h2>Clothing</h2>
<ul>
<li>Shirts</li>
<li>Dresses</li>
<li>Trousers</li>
<li>Skirts</li>
<li>Socks</li>
<li>Underwear</li>
</ul>
</div>
<div class="megaMenuList">
<h2>Accessories</h2>
<ul>
<li>Jewelry</li>
<li>Handbags</li>
<li>Shoes</li>
<li>Tights</li>
</ul>
</div>
I have a filter class that filters products residing inside the page.There is a function that works if someone checks the filters.
Filters are check-boxes where every check box contains different value.
What my filter function do is that it checks all the checked checkboxes from the page and then uses the data-* global variable present on the list tages to decide what element to show.
DOM structure of the items will be:
<body>
<ul class="products">
<li class="product" data-company="something" data-flavour="something"></li>
<li class="product" data-company="something" data-flavour="something"></li>
.
.
.
.
<li class="product" data-company="something" data-flavour="something"></li>
</ul>
</body>
Below one shows the the function that does the job.
this.filterGridProducts = function() {
$.ajax({
type: 'POST',
url: 'test12.php',
data: category,
success: function(data) {
$('#limitpage').html(data);
// $('.product').hide();
var filteredProducts =$('.product');
//filter by colour, size, shape etc
var filterAttributes = $('input[type="checkbox"]');
var selectedFiltersValues = [];
// for each attribute check the corresponding attribute filters selected
filterAttributes.each(function() {
if (this.checked) {
var currentFilter = $(this);
selectedFiltersValues.push("[data-" + currentFilter.attr('name') + "='" + currentFilter.val() + "']");
filteredProducts = filteredProducts.filter(selectedFiltersValues.join(','));
}
});
filteredProducts = filteredProducts.filter(function() {
return ($(this).attr('data-price') > first && $(this).attr('data-price') <= second);
});
//console.log($('.product').show());
filteredProducts.each(function(e) {
console.log($(this).html().show()); // not working
$(this).show(); // not working
})
filteredProducts.show(); // this one is not working as well.
}
});
};
filteredProducts does contain the elements that need to be filtered but I can't seem to show it.
Ajax call in the above functions loads all the elements present inside the db, The products that come from it are all hidden.
What could be the possible reason for the .show() to not work?
Update:
I have a list that is being created dynamically. Part of code that creates a list is:
<ul>
<?
foreach ($folders as $folder)
{
$folder = str_replace("{imap.gmail.com:993/imap/ssl}", "", $folder);
$folder2 = str_replace("[Gmail]/", "", $folder);
?>
<li>
<a><div id="box"><? echo $folder2; ?> </div></a>
</li>
<?}
</ul>
<div id="maillist"></div>
o/p of $folder
GMAIL/All Mail
GMAIL/Drafts
GMAIL/Important
o/p of $folder2
All Mail
Drafts
Important
what i want is that when a user clicks on All Mail, value corresponding to it (in this case: GMAIL/All Mail) should get pass to another script through ajax. The same process should follow for the other values in list also
ajax code
<script>
$(document).ready(function(){
$('#box').change(function(){
var boxid = $('#box').val();
console.log($('#box'))
if(boxid != 0)
{
$.ajax({
type:'post',
url:'a_fetchmaillist.php',
data:{id:boxid},
cache:false,
success: function(returndata){
$('#maillist').html(returndata);
console.log(returndata)
}
});
}
})
})
</script>
Can anyone tell if its possible to do what i want and if yes then how will it be done
First of all do not assign the same id multiple times, instead, set a class (eg box).
Then assign a data attribute for the specific folder ( eg. box-allMails ) and select that attribute on change:
foreach ($folders as $folder)
{
$folder = str_replace("{imap.gmail.com:993/imap/ssl}", "", $folder);
$folder2 = str_replace("[Gmail]/", "", $folder);
?>
<li>
<div class="box" data-folder="<? echo $folder2 ?>"><? echo $folder2; ?></div>
</li>
<?}
Then on change:
$(document).on('click', '.box', function() {
var folder = $(this).attr('data-folder');
// ajax call..
});
UPDATE
Important: You have to listen to 'click' event instead of 'change' because you click on a div, not on an input (I've changed the code).
Event delegation: Take note at the code:
$(document).on('click', '.dynamic-element', function() { .. })
instead of:
$('.element').on('click', function() { .. });
The second will not work because you are creating the elements dynamically.
Clickable: You do not have to insert an anchor tag to make the list item clickable unless you want to redirect to another page. In your case, you can style the .box div in order to get a cursor-pointer like this:
CSS
.box { cursor:pointer }
jQuery will take care of the rest (Check the example)
$(document).on('click', '.box', function() {
var folder = $(this).attr('data-folder');
alert('You clicked on: ' + folder);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><div class="box" data-folder="folderOne">Folder One</div></li>
<li><div class="box" data-folder="folderTwo">Folder Two</div></li>
<li><div class="box" data-folder="folderThree">Folder Three</div></li>
<li><div class="box" data-folder="folderFour">Folder Four</div></li>
</ul>
I want to add "product compare feature" in my website product list. I am wondering how can I make a Query String URL from product list page using jQuery. Looks like below one.
I need compare URL should be generated like below, and maximum product can be added as 4.
Compare Products
Fiddle: http://jsfiddle.net/taxjD/341/
I can handle these query string parameter on compare.html page.
<div id="container" class="hidden">
<p>There are 0 boxes</p>
**Compare**
</div>
<div>
<div>
<h1>Product Name 1</h1>
+ Add to compare
<span class="ProdId">123</span>
</div>
<div>
<h1>Product Name 2</h1>
+ Add to compare
<span class="ProdId">124</span>
</div>
<div>
<h1>Product Name 3</h1>
+ Add to compare
<span class="ProdId">125</span>
</div>
</div>
Jquery
$(".more").click(function() {
var id=$(this).next('.ProdId').html();
$("#container").append("<div class='box'> "+ id + "<a href='#'>x</a></div>");
var count = $(".box").length;
$("p").text("There are " + count + " boxes.");
$("#container").removeClass("hidden");
});
$(".box a").live("click", function() {
$(this).parent().remove();
var count = $(".box").length;
$("p").text("There are " + count + " boxes.");
});
You need to somehow keep track of the items that have been selected. That could be an array variable that you updated both on add and remove, but it could also be indicated in the .box elements you're creating. If you wrap the product ID in a span in the .box elements as well, you'll have an easier time targeting the ID:
$('<div/>', { 'class': 'box' })
.append($('<span/>', { class: 'prod-id', text: id }))
.append($('<a/>', { href: '#', text: 'x' }))
.appendTo('#container');
You could then do:
var ids = $('.box .prod-id')
.map(function(i, x) { return ['P', ++i, '=', $(this).text()].join(''); })
.toArray();
$('#container > a').attr('href', 'Compare.html?' + ids.join('&'));
Demo
Update:
Your additional requests are easily fulfilled now that we've established a way of retreiving the added products' IDs. Since we'll be reusing it, I've extracted getSelectedIds as a function of its own.
Now we just need to check its length to test the max 4 requirement, and its indexOf(id) to test whether the item was already added. If so, the code will just exit the .more click listener. You could show the user an error message at that point.
Updated demo