jQuery get many objects with same class and switch between them - javascript

Does anyone know how to grab many objects with same class in jQuery and then show previous object with same class by clicking prev button and next one by next btn? I'm just starting with programming and try to write recipies store and I stucked on that, I can grab value of element I click on but don't know how to switch between them using buttons
<div>
<button class="prev"></button>
<button class="next"></button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>
JQuery to grab value of recipie I clicked on
$(".recipies").on("click", function () {
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
})
UPDATED:
it works but let me ask one more question:) and thank you for your help so far! I decided to a bit improve my code to make it easier to style and update and I decided that every recipie will be separate ul, to make it easier to read etc
<div>
<button class="prev"></button>
<button class="next"></button>
<p class="showRecipies"></p>
<ul class="listOfRecipies">
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Drinks</li>
</ul>
</li>
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Vegetables</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Meet</li>
</ul>
</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Fruits</li>
</ul>
</li>
<li>
<ul class="particularRecipie">
<li class "timeOfPreparation>3:20</li>
<li class="recipies">Others</li>
</ul>
</li>
</div>
In this case I should just go higher through parent() property right? Like:
$(".recipies").on("click", function() {
$(".recipies.active").add($(this)).toggleClass("active");
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
});
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isLast){
$this.parent().parent().find(".recipies:first").trigger("click");
} else {
$this.next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isFirst){
$this.parent().parent().find(".recipies:last").trigger("click");
} else {
$this.prev().trigger("click");
}
});

You can use this code:
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
if(isLast){
$(this).parent().find(".recipies:first").trigger("click");
} else {
$(".recipies.active").next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
if(isFirst){
$(this).parent().find(".recipies:last").trigger("click");
} else {
$(".recipies.active").prev().trigger("click");
}
});
I've added $(".recipies.active").add($(this)).toggleClass("active"); to your .recipies click function, so we know what li is active/has been clicked
Demo
$(".recipies").on("click", function() {
$(".recipies.active").add($(this)).toggleClass("active");
var recipieValue = $(this).text();
var showRecipies = document.querySelector(".showRecipies");
showRecipies.innerHTML = recipieValue;
});
$(".next").click(function() {
var isLast = $(".recipies.active").is(":last-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isLast){
$this.parent().find(".recipies:first").trigger("click");
} else {
$this.next().trigger("click");
}
});
$(".prev").click(function() {
var isFirst = $(".recipies.active").is(":first-child");
var $this = $(".recipies.active") || $(".recipies:first");
if(isFirst){
$this.parent().find(".recipies:last").trigger("click");
} else {
$this.prev().trigger("click");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="prev">prev</button>
<button class="next">next</button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>

You can use the prev() and next() to cycle through the available recipies:
var rec = $('.recipies:first');
$('.showRecipies').html(rec.html());
$('.prev').click(function() {
rec = rec.prev('.recipies');
if (!rec.length) {
rec = $('.recipies:last');
}
$('.showRecipies').html(rec.html());
});
$('.next').click(function() {
rec = rec.next('.recipies');
if (!rec.length) {
rec = $('.recipies:first');
}
$('.showRecipies').html(rec.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="prev">prev</button>
<button class="next">next</button>
<p class="showRecipies"></p>
<ul>
<li class="recipies">Drinks</li>
<li class="recipies">Vegetables</li>
<li class="recipies">Meet</li>
<li class="recipies">Fruits</li>
<li class="recipies">Others</li>
</ul>
</div>

Next button:
$(".next").click(function () {
let currentRecipies = $('.recipies.current');
let currentRecipiesValue = $('.recipies.current').text();
let currentRecipiesIndex = $('.recipies.current').index();
let nextRecipiesIndex = currentRecipiesIndex + 1;
let nextRecipies = $('.recipies').eq(nextRecipiesIndex);
currentRecipies.removeClass('current');
let showRecipies = document.querySelector(".showRecipies");
if (nextRecipiesIndex == ($('.recipies:last').index()+1)) {
$('.recipies').eq(0).addClass('current');
showRecipies.innerHTML = currentRecipiesValue
} else {
nextRecipies.addClass('current');
showRecipies.innerHTML = currentRecipiesValue
}
})
Prev:
$(".prev").click(function () {
let currentRecipies = $('.recipies.current');
let currentRecipiesValue = $('.recipies.current').text();
let currentRecipiesIndex = $('.recipies.current').index();
let nextRecipiesIndex = currentRecipiesIndex - 1;
let nextRecipies = $('.recipies').eq(nextRecipiesIndex);
currentRecipies.removeClass('current');
let showRecipies = document.querySelector(".showRecipies");
if (nextRecipiesIndex == ($('.recipies:first').index() - 1)) {
$('.recipies').eq(4).addClass('current');
showRecipies.innerHTML = currentRecipiesValue
} else {
nextRecipies.addClass('current');
showRecipies.innerHTML = currentRecipiesValue
}
})

Related

Why i get plus three on my index when i click on load more button

//Fetch Posts
fetch(`https://jsonplaceholder.typicode.com/posts`)
.then((response) => response.json())
.then((data) => {
//Content load function start here
let count = 12;
function contentLoad() {
let showPosts = "";
let modalOutput = "";
for (let i = 0; i < count; i++) {
// First on load show 12 posts as limited, after that can load more on button
showPosts += `
<ul class='list-group my-4'>
<li class='list-group-item'><span class='fw-bold'>ID: </span> ${
data[i].id
}</li>
<li class='list-group-item'><span class='fw-bold'>Title: </span> ${
data[i].title
}</li>
<li class='list-group-item'><span class='fw-bold'>Post: </span> ${data[
i
].body
.split(" ")
.splice(0, 3)
.join(" ")}</li>
</ul>`;
document.querySelector(".post-content").innerHTML = showPosts;
document.getElementById("loading").style.display = "none";
// Add a listener to all posts to open modal when clicking
document.querySelectorAll("ul").forEach((element, index) => {
element.addEventListener("click", function () {
document
.getElementById("close")
.addEventListener("click", function () {
document.getElementById("myModal").style.display = "none";
});
// Here we get data for modal
fetch(
`https://jsonplaceholder.typicode.com/users/${data[index].userId}`
)
.then((response) => response.json())
.then((dataUser) => {
modalOutput = `
<ul class='list-group my-4'>
<li class='list-group-item'><span class='fw-bold'>ID:</span> ${data[index].id}</li>
<li class='list-group-item'><span class='fw-bold'>FullName:</span> ${dataUser.name}</li>
<li class='list-group-item'><span class='fw-bold'>Title:</span> ${data[index].title}</li>
<li class='list-group-item'><span class='fw-bold'>Post:</span> ${data[index].body}</li>
<li class='list-group-item'><span class='fw-bold'>Location:</span> ${dataUser.address.city}</li>
</ul>`;
document.getElementById("myModal").style.display = "block";
document.querySelector(".modal-data").innerHTML = modalOutput;
fetch(
`https://jsonplaceholder.typicode.com/comments?postId=${data[index].id}`
)
.then((response) => response.json())
.then((dataComment) => {
// Here I show a modal with specific data
document.getElementById("myModal").style.display = "block";
document.querySelector(".modal-data").innerHTML = `
<ul class='list-group my-4'>
<li class='list-group-item'><span class='fw-bold'>ID:</span> ${data[index].id}</li>
<li class='list-group-item'><span class='fw-bold'>User Name:</span> ${dataUser.name}</li>
<li class='list-group-item'><span class='fw-bold'>Title:</span> ${data[index].title}</li>
<li class='list-group-item'><span class='fw-bold'>Post:</span> ${data[index].body}</li>
<li class='list-group-item'><span class='fw-bold'>Location:</span> ${dataUser.address.city}</li>
<li class='list-group-item'><span class='fw-bold'>Company:</span> ${dataUser.company.name}</li>`;
// Here i loop odd comments
let comments = "";
// document.getElementById("loading-modal").style.display =
// "none";
for (let c = 0; c < dataComment.length; c++) {
if (dataComment[c].id % 3 == 0) {
comments += `
<ul class='item-group'>
<li class='list-group-items'> <span class='fw-bold'>Id:</span> ${dataComment[c].id}</li>
<li class='list-group-items'> <span class='fw-bold'>Email:</span> ${dataComment[c].email}</li>
<li class='list-group-items'> <span class='fw-bold'>Comment:</span> ${dataComment[c].body}</li>
</ul>`;
document.querySelector(`.modal-comments`).innerHTML =
comments;
}
}
})
.catch((error) => {
throw console.log(error);
});
})
.catch((error) => {
throw console.log(error);
});
});
});
}
}
// Load more posts on the button click, the problem starts when I try
// third time to load posts, they load posts but the id doesn't match
// When I click on a post they open me modal, but the ID doesn't match, they add 3 on ID (Index)
document.querySelector(".btn").addEventListener("click", function () {
count = count + 12;
if (count > 96) {
document.querySelector(".btn").style.display = "none";
document.querySelector(".alert").style.display = "block";
}
contentLoad();
});
.catch((error) => {
throw console.log(error);
});

This code is working but after working Why this code is showing error

here is the html part ..
var removeButton = document.getElementById("remove");
removeButton.addEventListener("click", removeItem);
function removeItem() {
var list = document.getElementById("list");
var listItems = list.getElementsByTagName("li");
var last = listItems[listItems.length - 1];
list.removeChild(last);
if (last == listItems.length - 1) {
document.getElementById("remove").disabled = true;
}
}
<ul id="list">
<li class="abc">cold cereal</li>
<li class="abc">Ice cream</li>
<li class="abc">Honey</li>
<li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove item</button>
clicked on the remove button and its removing the items from the list after all the items are deleted from the list its showing the error .
when i run this code every thing is working fine but when all the items are deleted from the list after deleting all the list items from the list when i press the button once more it shows the error
this way
const
removeButton = document.getElementById('remove')
, list = document.getElementById('list')
;
removeButton.addEventListener("click", removeItem);
function removeItem()
{
let
listItems = list.querySelectorAll('li')
, lastRef = listItems.length - 1
;
list.removeChild(listItems[lastRef] );
if (lastRef === 0) {
removeButton.disabled = true;
}
}
<ul id="list">
<li class="abc">cold cereal</li>
<li class="abc">Ice cream</li>
<li class="abc">Honey</li>
<li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove last item</button>
i don't know why you used this
if( last == listItem.length - 1)
{
document.getElementById('remove').disable = true;
}
try this
if(listItem.length - 1 === 0){
document.getElementById("remove").disabled = true;
}
}
When your all nodes are deleted then you can't perform delete operation you will have to apply a condition to overcome this
Replace your removeItem function code with the given below-
function removeItem() {
var list = document.getElementById("list");
var listItems = list.getElementsByTagName("li");
if (listItems.length > 0) {
var last = listItems[listItems.length - 1];
list.removeChild(last);
}
else{
alert("can't delete")
}
}

Search Filter with Javascript

I am trying to build a basic search filter where you search and a certain image appears on screen and I am trying to do this with javascript or simple jquery , I cannot seem to make the search work, and I am also wondering if it is possible to do a search based on a class name?
Here is my HTML code
<form onkeyup "function()" >
<input type="search" id = "myInput" placeholder="Search.." name="search" >
</form>
<ul id ="myUL">
<li class="SupernaturalCookbook"><img src="Images/SupernaturalCookbookCard.jpg" alt="SupernaturalCookbook"></li>
<li class="MarkOfAthena"><img src="Images/MarkOfAthenaCard.jpg" alt="MarkOfAthena"></li>
<li class="Instinct"><img src="Images/InstinctCard.jpg" alt="Instinct"></li>
<li class="CaminoIsland"><img src="Images/CaminoIslandCard.jpg" alt="caminoisland"></li>
<li class="TheLuckyOne"><img src="Images/TheLuckyOneCard.jpg" alt="theluckyone"></li>
<li class="TheWhistler"><img src="Images/TheWhistlerCard.jpg" alt="thewhistler"></li>
<li class="Greenlights"><img src="Images/GreenlightsCard.jpg" alt="greenlights"></li>
<li class="SeaOfMonsters"><img src="Images/SeaOfMonstersCard.jpg" alt="seaofmonsters"></li>
<li class="SerpentShadows"><img src="Images/SerpentShadowsCard.jpg" alt="serpentshadows"></li>
<li class="FromCrookToCook"><img src="Images/FromCrookToCookCard.jpg" alt="fromcrooktocook"></li>
</ul>
Here is my Javascript code:
var input = document.getElementById('myInput');
input.onkeyup = function () {
var filter = myInput.value.toUpperCase();
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
var name = lis[i].getElementsByClassName('class')[0].innerHTML;
if (name.toUpperCase().indexOf(filter) == 0)
lis[i].style.display = 'list-item';
else
lis[i].style.display = 'none';
}
In addition to what others added, please keep in mind that onkeyup only triggers when someone releases a key. However, there are other ways to change the input of an input field such as cut, paste, clear, etc. To make sure you have covered all the aspects, you can wrap your code in a named function and bind it to the following events
function search_images(){
///code goes here
}
input.onkeyup = search_images
input.onchange = search_images
input.onpaste = search_images
input.oncut = search_images
input.oninput = search_images
Also, be sure to RESET the filter if the input is empty. An alternative solution is as follows:-
function search_images() {
let filter = this.value.toUpperCase();
let lis = Array.from(document.getElementsByTagName('li'));
if (filter.length > 0) {
lis.forEach(li => {
if (Array.from(li.classList).join(" ").toUpperCase().indexOf(filter) >= 0) {
li.style.display = "list-item"
} else {
li.style.display = "none"
}
})
} else {
lis.forEach(li => li.style.display = "list-item")
}
}
const input = document.getElementById('myInput');
input.onkeyup = search_images
input.onchange = search_images
input.onpaste = search_images
input.oncut = search_images
input.oninput = search_images
<form>
<input type="search" id="myInput" placeholder="Search.." name="search">
</form>
<ul id="myUL">
<li class="SupernaturalCookbook">
<img src="Images/SupernaturalCookbookCard.jpg" alt="SupernaturalCookbook">
</li>
<li class="MarkOfAthena">
<img src="Images/MarkOfAthenaCard.jpg" alt="MarkOfAthena">
</li>
<li class="Instinct">
<img src="Images/InstinctCard.jpg" alt="Instinct">
</li>
<li class="CaminoIsland">
<img src="Images/CaminoIslandCard.jpg" alt="caminoisland">
</li>
<li class="TheLuckyOne">
<img src="Images/TheLuckyOneCard.jpg" alt="theluckyone">
</li>
<li class="TheWhistler">
<img src="Images/TheWhistlerCard.jpg" alt="thewhistler">
</li>
<li class="Greenlights">
<img src="Images/GreenlightsCard.jpg" alt="greenlights">
</li>
<li class="SeaOfMonsters">
<img src="Images/SeaOfMonstersCard.jpg" alt="seaofmonsters">
</li>
<li class="SerpentShadows">
<img src="Images/SerpentShadowsCard.jpg" alt="serpentshadows">
</li>
<li class="FromCrookToCook">
<img src="Images/FromCrookToCookCard.jpg" alt="fromcrooktocook">
</li>
</ul>
If you want to filter by class name, replace this line ...
var name = lis[i].getElementsByClassName('class')[0].innerHTML;
... with this:
var name = lis[i].className;
var input = document.getElementById('myInput');
input.onkeyup = function () {
var filter = input.value.toUpperCase();
var lis = document.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
var name = lis[i].className; // takes the classname
if (name.toUpperCase().indexOf(filter) >= 0) //Changed this part
lis[i].style.display = 'list-item';
else
lis[i].style.display = 'none';
}
}
indexOf method returns -1 if not found, else it will be greater than or equal than 0.

change text color of matching text from input in javascript

Here is my code
And I am trying to change the color of any match in the <li> elements that matches the text in the <input> element. So if you type lets say "this is a simple text" the result should look like this:
<input value="this is a simple text" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy <span style="color:red">this</span> <span style="color:red">is</span> really <span style="color:red">simple</span> stuff </li>
<li id="li-id-2"> <span style="color:red">this</span> <span style="color:red">is</span> it</li>
<li id="li-id-3"> there <span style="color:red">is</span> something here</li>
<li id="li-id-4"> plain <span style="color:red">text</span> file</li>
</ul>
Any help would be appreciated.
Thank you.
You can remove the delay function if you like, but this would lead to a performance loss:
// https://stackoverflow.com/a/9310752/1636522
RegExp.escape = function (text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
};
window.addEventListener('load', function () {
var wrapper = '<span style="background:yellow">$&</span>';
var input = document.getElementById('term');
var list = document.getElementById('ul-id');
var items = list.getElementsByTagName('li');
var l = items.length;
var source = Array.prototype.map.call(
items, function (li) { return li.textContent; }
);
var cmp = function (a, b) {
return b.length - a.length;
};
var delay = function (fn, ms) {
var id, scope, args;
return function () {
scope = this;
args = arguments;
id && clearTimeout(id);
id = setTimeout(function () {
fn.apply(scope, args);
}, ms);
};
};
term.addEventListener('keyup', delay(function () {
var i, re, val;
if (val = this.value.match(/[^ ]+/g)) {
val = val.sort(cmp).map(RegExp.escape);
re = new RegExp(val.join('|'), 'g');
for (i = 0; i < l; i++) {
items[i].innerHTML = source[i].replace(re, wrapper);
}
}
else {
for (i = 0; i < l; i++) {
items[i].textContent = source[i];
}
}
}, 500));
});
<input value="" id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
Similar topic: https://stackoverflow.com/a/20427785/1636522.
I don't know if it is possible with only RegEx, but here is a jQuery solution:
$('#term').change(function() {
var inpArr = $(this).val().split(" ");
$('#ul-id li').each(function() {
var liArr = $(this).text().split(" ");
var txt = "";
$.each(liArr, function(i, v) {
if(inpArr.indexOf(v) > -1) {
txt += "<span class='red'>"+ v +"</span> ";
} else {
txt += v + " ";
}
});
$(this).html(txt);
});
});
span.red {
color: red;
}
And the working fiddle: https://jsfiddle.net/ermk32yc/1/
Plain JS solution
var list = document.querySelector('#ul-id'),
listItem,
listItems,
term = document.querySelector('#term'),
oldRef = list.innerHTML,
oldValue;
term.addEventListener('keyup', function () {
var regExp,
value = term.value;
if (oldValue !== value) {
oldValue = value;
// Reset
list.innerHTML = oldRef;
if (value.trim() !== '') {
listItems = list.querySelectorAll('#ul-id li');
regExp = new RegExp(term.value, 'g');
// Perform matching
for (var i = 0; i < listItems.length; i++) {
listItem = listItems[i];
listItem.innerHTML = listItem.innerHTML.replace(regExp, function (match) {
return '<span class="matched">' + match + '</span>';
});
}
}
}
}, false);
.matched {
color: red;
}
<input id="term"/>
<ul id="ul-id" >
<li id="li-id-1"> hello budy this is really simple stuff </li>
<li id="li-id-2"> this is it</li>
<li id="li-id-3"> there is something here</li>
<li id="li-id-4"> plain text file</li>
</ul>
You might do something like this
$('#term').change(function (i) {
var terms = $('#term').val().split(" ");
$('#ul-id > li').each(function (i, el) {
var val = $(el).html().replace(/<[^<]+>/g, ''),
match;
terms.forEach(function (term) {
val = val.replace(new RegExp(term, 'g'),
'<span style="color:red">' + term + '</span>');
});
$(el).html(val);
});
});
https://jsfiddle.net/1vm0259x/5/
You can use the below solution if there is no html contents in the li elemnets
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var lis = [].slice.call(document.querySelectorAll('#ul-id li'));
lis.forEach(function(el) {
el.dataset.text = el.innerHTML;
});
document.querySelector('#term').addEventListener('change', function() {
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
lis.forEach(function(el) {
el.innerHTML = el.dataset.text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
})
});
});
.highlight {
color: red;
}
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
With jQuery
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
$('#term').on('change keyup', function() {
//$('#ul-id li .highlight').contents().unwrap();//remove previous highlights
var parts = this.value.split(' ').map(function(value) {
return '\\b' + RegExp.escape(value) + '\\b';
});
var regex = new RegExp(parts.join('|'), 'g');
$('#ul-id li ').each(function() {
var text = $(this).text();
$(this).html(text.replace(regex, function(part) {
return '<span class="highlight">' + part + '</span>'
}))
})
});
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="term" />
<ul id="ul-id">
<li id="li-id-1">hello budy this is really simple stuff</li>
<li id="li-id-2">this is it</li>
<li id="li-id-3">there is something here</li>
<li id="li-id-4">plain text file</li>
</ul>
you can handle blur event or you can copy paste the inner function code to wherever it is required. this is the guide code here you can more explore match function as per your requirement and then can traverse your li elements as shown below.
$('#term).blur(function() {
$('#ul-id li').foreach(function()
{
if($(this).text().match($("#term").text()))
{
///set/change here color of li element
$(this).css('color', 'red');
}
}
}

Apply multiple filter categories to a list of <li>(s) with javascript

I have this fiddle and I want to know how I can implement filtering function based on two categories. when someone click the filter, it should get the values from both the current filters selection, hide the list and show only the filter result. Any idea on how to implement this step? any help would be appreciated!!
<ul style='list-style-type: none;' class="filter1">
<li><span class="filtercat1">red</span>
</li>
<li><span class="filtercat1">blue</span>
</li>
<li><span class="filtercat1">yellow</span>
</li>
<li><span class="filtercat1">all</span>
</li>
</ul> <span id="filterbutton1">
« Previous
Next »
</span>
<ul style='list-style-type: none;' class="filter2">
<li><span class="filtercat2">orange</span>
</li>
<li><span class="filtercat2">apple</span>
</li>
<li><span class="filtercat2">papaya</span>
</li>
<li><span class="filtercat2">all</span>
</li>
</ul> <span id="filterbutton2">
« Previous
Next »
</span>
<ul id='list'>
<li class="">red orange</li>
<li class="">red apple</li>
<li class="">red papaya</li>
<li class="">blue orange</li>
<li class="">blue apple</li>
<li class="">blue papaya</li>
<li class="">yellow orange</li>
<li class="">yellow apple</li>
<li class="">yellow papaya</li>
</ul>
<span id="filterbutton">
filter
<span id="resetbutton">
reset
$(function () {
var all = $('.filtercat1').addClass("passiv");
var i = -1;
$('#prev' ).click(function () {
ctrlbutton(i = !i ? all.length - 1 : --i);
});
$('#next').click(function () {
ctrlbutton(i = ++i % all.length);
}).click();
function ctrlbutton(ele) {
all.removeClass("active").addClass("passiv");
all.eq(ele).removeClass("passiv").addClass("active");
}
})
$(function () {
var all = $('.filtercat2').addClass("passiv");
var i = -1;
$('#prev2').click(function () {
ctrlbutton(i = !i ? all.length - 1 : --i);
});
$('#next2').click(function () {
ctrlbutton(i = ++i % all.length);
}).click();
function ctrlbutton(ele) {
all.removeClass("active").addClass("passiv");
all.eq(ele).removeClass("passiv").addClass("active");
}
})
fiddle: http://jsfiddle.net/BlacBunny/5tfcuy1w/
Use this code
$("#list").find("li").each(function(){
this.className = "all "+this.innerHTML;
});
$("#filter").click(function(){
var class1 = $(".filter1").find(".active").text();
var class2 = $(".filter2").find(".active").text();
$("#list").find("li").addClass("passiv").end().find("."+class1+"."+class2)
.removeClass("passiv").addClass("active");
});
$("#reset").click(function(){
$("#list").find("li").addClass("active").removeClass("passiv");
});
I have not optimized this code. You are using dom ready function two times which is actually not required.
You can see the fiddle here
See Fiddle
This function will be called every time the filters are modified. The values of filter1 and filter2 must be modified per click to the filter buttons.
var filter1 = 'red'; // initial value of filter1
var filter2 = 'orange'; // initial value of filter2
function filterList() {
var list = $('#list li');
list.each(function(index, item) {
var itemContents = $(item).text();
if (itemContents.indexOf(filter1) >= 0 && itemContents.indexOf(filter2) >= 0) {
$(item).show();
} else {
console.log('hide ' + itemContents);
}
});
}
Fiddle
$("#filter").click(function() {
var filterCat1 = $(".filter1 .active").text();
var filterCat2 = $(".filter2 .active").text();
$("#list li").each( function( index, element ){
var text = $(element).text();
if((text.indexOf(filterCat1) < 0 && filterCat1 != "all")
|| (text.indexOf(filterCat2) < 0 && filterCat2 != "all"))
$(element).removeClass("active").addClass("passiv");
else
$(element).removeClass("passiv").addClass("active");
});
});
Try the contains selector
$('#filter').click(function() {
$("#list li").addClass("passiv");
var filter1 = $(".filter1 span.active").text();
var filter2 = $(".filter2 span.active").text();
var filter= (filter1 == "all" ? "" : filter1) + " " + (filter2 == "all" ? "" : filter2);
$('#list li:contains("' + filter + '")').removeClass("passiv");
});
http://jsfiddle.net/5tfcuy1w/10/

Categories