jquery toggle visibility if has class - javascript

I've collected all my portfolio items into an array as seen here.
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
items.toggle("slow");
}
The function parameter is a string class name for example "Print". What I want to do is hide the portfolio items which don't have the class 'filter' and the ones that do, make them visible.

For your question:
What I want to do is hide the portfolio items which don't have the class 'filter' and the ones that do, make them visible.
You can make this:
function SetPortfolioItems(filter) {
var str = filter.toLowerCase();
var invalidItems = $( ".portfolio-item:not(."+str+")");
invalidItems.hide("slow");
var validItems = $( ".portfolio-item." + str );
validItems.show("slow");
}
SetPortfolioItems('filter');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="portfolio-item">item 1</div>
<div class="portfolio-item filter">item 2</div>
<div class="portfolio-item">item 3</div>
<div class="portfolio-item filter">item 4</div>
<div class="portfolio-item">item 5</div>
<div class="portfolio-item">item 6</div>

Use jQuery not() function.
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
items.not('.' + filter).hide("slow");
}

Use hasClass by jQuery :
jQuery Docs
function SetPortfolioItems(filter) {
items = $( ".portfolio-item" );
if (items.hasClass(filter)) {
...
} else {
...
}
}

Related

toggle div using for loops

just wondering what went wrong.. i have two div named click_1 and click_2.. and i want to toggle the div named hide corresponding with their numbers.. lets say click_1 with hide_1 and click_2 with hide_2.. but when i ran the code only click_1 is functioning .. what seems to be wrong... newbie here.. recently learned jquery
<div id='click_1'>
<div id='hide_1'></div>
</div>
<div id='click_2'>
<div id='hide_2'></div>
</div>
<script>
function toggle_div(id_A,id_B){
for(var i=0; i<3; i++){
var new_A = id_A + i;
var new_B = id_B + i;
$(new_A).click(function(){
$(new_B).toggle();
});
}
}
toggle_div('click_','hide_');
</script>
The issue is because your id selectors are missing the # prefix:
toggle_div('#click_', '#hide_');
However you should note that you will also need to use a closure for this pattern to work otherwise the new_B element will always be the last one referenced in the for loop.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
click 1
<div id='hide_1'>hide 1</div>
</div>
<div id='click_2'>
click 2
<div id='hide_2'>hide 2</div>
</div>
<script>
function toggle_div(id_A, id_B) {
for (var i = 1; i < 3; i++) {
var new_A = id_A + i;
var new_B = id_B + i;
(function(a, b) {
$(a).click(function() {
$(b).toggle();
})
})(new_A, new_B);
}
}
toggle_div('#click_', '#hide_');
</script>
As you can see this is very verbose, rather complicated and hardly extensible. A much better approach is to use generic classes and DOM traversal to repeat the same logic on common HTML structures.
To achieve this put common classes on the elements to be clicked and the elements to toggle. Then in the single click event handler you can use the this keyword to reference the element which was clicked, then find() the element to toggle within that. Something like this:
$(function() {
$('.click').click(function() {
$(this).find('.hide').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click">
click 1
<div class="hide">hide 1</div>
</div>
<div class="click">
click 2
<div class="hide">hide 2</div>
</div>
<div class="click">
click 3
<div class="hide">hide 3</div>
</div>
Also note that this pattern means that you can have an infinite number of .click elements with matching .hide content without ever needing to update your JS code.
It is better not to use for loop for click event ! If you have id like that your can handle by that clicked id split ....
$("[id^='click_']").on("click",function () {
$('#hide_'+this.id.split('_')[1]).toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='click_1'>
Click1
<div id='hide_1'>hide1</div>
</div>
<div id='click_2'>
Click2
<div id='hide_2'>hide2</div>
</div>

JavaScript: If condition based on div ID

I'm making a web app for a school project and I'm creating a function for a click event on my ".tile" class. Inside the tile class I have 7 tile IDs; "#tile1", "#tile2" etc. I want to make an 'if' condition to check the ID of the tile clicked e.g. if (ID == "#tile2") {}. Is something like this possible or do I need to make functions for each individual tile? The rest of the function is fine I only need help with the if statement. Sorry if this is really easy I'm fairly new.
It is possible. You can do :
$('.tile').click(function(){
var id = $(this).attr('id');
if(id === 'tile2'){
// do smthing
} else if(id === 'tile3'){
} ...
});
Where $(this) is the clicked element
You could also use a switch case to switch between your id's. See the doc https://www.w3schools.com/js/js_switch.asp
You could attach the click event listener on the class .tile and get the "clicked" tile's id by $(this).attr('id'), please see follow:
$(".tile").click(function(){
let id = $(this).attr('id');
console.log("Clicked on div: " + id);
if(id === "tile3")
console.log("Yes, it's the third");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>What's the third?</p>
<div id="tile1" class="tile">tile 1</div>
<div id="tile2" class="tile">tile 2</div>
<div id="tile3" class="tile">tile 3</div>
<div id="tile4" class="tile">tile 4</div>
<div id="tile5" class="tile">tile 5</div>
I hope it helps you, bye.

make links with javascript/jquery from html class

in my site have 3 box, how create with js a link from a html class
example my box is this:
<div class="box1">content</div>
<div class="box2">content</div>
<div class="box3">content</div>
how create a link for class box1,box2,box3
The question is ambiguous. if this is what you want:
<div id = "box1" class="box1">content</div>
<script>
var x = document.getElementsByClassName("box1");
$( ".box1" ).replaceWith( "content" );
</script>
I'm guessing this is what you are trying to do, turning the class into a link. http://jsfiddle.net/xthne2bm/1/
HTML
<div class="box1">content</div>
<div class="box2">content</div>
<div class="box3">content</div>
JQuery
$('[class^="box"').each(function () {
var link = $(this).attr('class');
$(this).wrapInner('<a>').find('a').attr('href', link);
});

How can I dynamically generate a jQuery selector?

I have a page with multiple divs generated dynamically via PHP/MySQL. The div class names are also generated dynamically.
<div class="1er45">Test 1</div>
<div class="25dd58">Test 2</div>
<div class="87f77">Test 3</div>
<div class="87fffas">Test 4</div>
<div class="1er45">Test 1</div>
<div class="25dd58">Test 2</div>
<div class="87fffas">Test 4</div>
<div class="8asdf">Test 5</div>
<div class="25dd58">Test 2</div>
<div class="87fffas">Test 4</div>
<div>...</div>
How can I modify this jQuery selector to match all of the dynamically generated div class names above? I only want to show the first div if there are multiple divs with the same class name.
<script>
$('.classname').not(':first').hide();
</script>
From what I understand probably you need to iterate over all div's and hide all same class names occurrences grater than 1 :
$( 'div[class]' ).each( function() {
$( 'div.' + $( this ).attr( 'class' ).replace( /\s/g, '.' ) + ':gt(0)' ).hide();
});
jsFiddle
I don't really see the point of having a class being dynamically generated.
If you know the pattern of these "ids", you can catch them with a regex.
Assuming that you are only ever going to have one class value in each of those <div>'s, you could acheive what you are asking for in the following code:
var $firstDiv = $("div:first");
var sFirstClass = $firstDiv.attr("class");
if ($("." + sFirstClass).length < 2) {
$firstDiv.hide();
}
That code would:
Retrieve the first div
Get it's class attribute value
Checks to see if there is more than one element with that class value
Hides the first element, if there is not
Iterate through each div, counting occurrences of each class name. Then for each collected class name, hide repeats.
var classNames = {};
$('div').each(function(){
var c = $(this).attr('class');
classNames[c] ? classNames[c]++ : classNames[c] = 1;
});
for (var c in classNames) {
if (classNames[c] > 1)
$('div.' + c).not(':first').hide();
}
http://jsfiddle.net/ne770a5g/

Elegant way to toggle visibility of divs in the same display area

I have 3 divs that contain a hidden field each:
<div class="item-wrapper">
<div class="item-title">Button 1</div>
<div class="hidden-field>Some hidden data</div>
</div>
<div class="item-wrapper">
<div class="item-title">Button 2</div>
<div class="hidden-field>Some more hidden data</div>
</div>
<div class="item-wrapper">
<div class="item-title">Button 3</div>
<div class="hidden-field>Even more hidden data</div>
</div>
My jQuery looks like this:
$( ".item-title" ).click(function() {
$( this ).next().slideToggle( "slow" );
$( this ).toggleClass( "item-active" );
});
The hidden-field divs have an absolute position and are displayed below the three wrappers. I want to find a way to show only one hidden field at a time, which basically means that if any hidden-field is visible at the time of the click, it needs to be hidden first.
Is there an elegant way of doing this or will I have to switch from slideToggle() to hide() and show() with conditionals?
Toggle is not always a good option. It is only useful for simple open/close items.
Try something that operates specifically on the chosen item and all the unselected ones (using not).
http://jsfiddle.net/gu6w8Lxb/
$( ".item-title" ).click(function() {
var $this = $(this);
$( ".item-title" ).not($this).removeClass("item-active").next().slideUp();
$this.addClass("item-active").next().slideDown();
});
Which can shorten further to:
var $items = $(".item-title");
$items.click(function() {
var $this = $(this);
$items.not($this).removeClass("item-active").next().slideUp();
$this.addClass("item-active").next().slideDown();
});
if you want the current item to toggle open/closed, test for its active class:
http://jsfiddle.net/gu6w8Lxb/1/
var $items = $(".item-title");
$(".item-title").click(function () {
var $this = $(this);
if ($this.hasClass("item-active")) {
$this.removeClass("item-active").next().slideUp();
} else {
$items.not(this).removeClass("item-active").next().slideUp();
$this.addClass("item-active").next().slideDown();
}
});

Categories