Only has class show, other divs hide via jQuery - javascript

HTML:
<div>
<h3>Past Events</h3>
<section class="event past-event">
. ..
</section>
<section class="event">
...
</section>
</div>
I want only if has 'Past Events' title, show past-event, hide event div via jQuery. How can I do it?

Check the text of the h3
function showSections() {
if ($("div h3").text() == "Past Events") {
$(".event").hide();
$(".past-event").show();
} else {
$(".event").hide();
$(".event:not(.past-event)").show();
}
}
A unique ID on the h3 would probably help quite a bit, the function above is pretty generic.

I think you are looking for this:
$("h3:contains('Past Events')").siblings("section.event").hide();
$("h3:contains('Past Events')").siblings("section.past-event").show();
If you can be more specific what you are trying to do, that can help write the exact code.

Related

In javascript, how do I remove previously clicked sibling div, so that only one answer displays at a time?

I must use a for loop to go through the h2 elements in the array and remove the class attribute for all h2 elements that aren’t the one that has been clicked. I also need to remove the class attributes for all of the div siblings of the h2 elements that weren’t clicked, but I am not sure how to do this. The code I am trying to use is under the "//remove all other answers" comment. Please help me out, thanks!
var toggle = function() {
var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag's sibling div tag
// toggle plus and minus image in h2 elements by adding or removing a class
if (h2.hasAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "minus");
}
// toggle div visibility by adding or removing a class
if (div.hasAttribute("class")) {
div.removeAttribute("class");
} else {
div.setAttribute("class", "open");
}
//remove all other answers
var faqs = $("faqs");
var h2Elements = faqs.getElementsByTagName("h2");
for (var i = 0; i < h2Elements.length; i++ ) {
if(!h2Elements.onclick) {
h2.removeAttribute("class", "minus");
} else {
h2Elements.onclick;
}
}
};
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2><a href="#" >What is JavaScript?</a></h2>
<div id="1">
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2>What is jQuery?</h2>
<div id="2">
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop websites.
</p>
</div>
<h2>Why is jQuery becoming so popular?</h2>
<div id="3">
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
This example should accomplish what you've outlined in your question. Here I'm looping through all H2 elements and processing the one that was clicked separately.
$('h2').on('click',function(){
var thisH2 = this;
$('h2').each(function(){
if (this === thisH2){
if ($(this).next().is(":visible")){
$(this).removeClass('plus').addClass('minus');
$(this).next().hide();
}else{
$(this).removeClass('minus').addClass('plus');
$(this).next().toggle();
}
}else{
$(this).removeClass('plus').addClass('minus');
$(this).next().hide();
}
});
});
h2{
cursor:pointer;
}
h2:hover{
text-decoration:underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2 class="minus">What is JavaScript?</h2>
<div class="answer" style='display:none'>
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2 class="minus">What is jQuery?</h2>
<div class="answer" style='display:none'>
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop websites.
</p>
</div>
<h2 class="minus">Why is jQuery becoming so popular?</h2>
<div class="answer" style='display:none'>
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
There is an easy common pattern for your type of problem. Give all questions a single, shared classname. Then on click
use document.getElementsByClassName with the shared classname and apply css display:"none" (or a class that achieves this style) on all elements
set display:"block" or display:"inline" on the current selection
You've wrapped all this code in your toggle function, but the function is not called anywhere.
You should attach the event listener to your h2 tags after defining them with jQuery.
The order of your set/remove attributes is a little off.
Try coming this working example to your code:
var h2 = $("h2");
h2.on('click', function() {
for (var i = 0; i < h2.length; i++) {
if (h2[i] !== this) {
h2[i].setAttribute('class', 'red');
} else {
h2[i].removeAttribute('class', 'red');
}
}
})
I've use the example class red here if you wanted to say, toggle the color in your CSS. You can use whatever class here in place of my example.
Hope this helps. What I have done is I hide all div(and remove class red from all h2 tag other than one which is click in for loop) and toggle clicked h2 and it's sibling.
function func(e){
var x=document.getElementsByClassName("ans");
for(var i=0;i<x.length;i++){
if(x[i].classList.value.indexOf("hide")<0 && x[i]!==e.nextElementSibling){
x[i].classList.toggle("hide");
x[i].previousElementSibling.classList.toggle("red");
}
}
e.classList.toggle("red");
e.nextElementSibling.classList.toggle("hide");
}
.red{
background-color:red;
}
.hide{
display:none;
}
<body>
<main id="faqs">
<h1>JavaScript FAQs</h1>
<h2 onclick="func(this)"><a href="#" >What is JavaScript?</a></h2>
<div id="1" class="ans hide">
<p>JavaScript is a is a browser-based programming language
that makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2 onclick="func(this)">What is jQuery?</h2>
<div id="2" class="ans hide">
<p>jQuery is a library of the JavaScript functions that you're most likely
to need as you develop websites.
</p>
</div>
<h2 onclick="func(this)">Why is jQuery becoming so popular?</h2>
<div id="3" class="ans hide">
<p>Three reasons:</p>
<ul>
<li>It's free.</li>
<li>It lets you get more done in less time.</li>
<li>All of its functions are cross-browser compatible.</li>
</ul>
</div>
</main>
</body>
To help you identify your sections from your Subheadings
Add this to all sections you can use different identifiers
I'd suggest adding a class or attribute
<h2>What is JavaScript?</h2>
<div class="section" id="1">
This will enable us to select all the divs will the class section
const sections = document.querySelectorAll('.section')
Then we can loop over them all and add the minus class I'd suggest just adding this in the mark up if you intend this to be your default state.
sections.forEach(el => {
el.classList.add('minus')
});
Now we can loop over all your anchor tags I'd suggest giving them an identifier such as a class to separate them from other anchor tags but the example i'll just select all the anchor tags.
We attach a function reference to the on click of the element called openSection which we'll define shortly.
document.querySelectorAll('a').forEach((el, index) => {
el.onclick = openSection;
})
Now, this is the function that will toggle your minus and remove it from other items
Your function gets passed an event which will contain the information we need to get the correct section to hide. We loop through the sections and remove minus with toggle if it matches the element clicked and then any other item if it doesn't have minus it gets added on to make sure it's hidden.
function openSection(e) {
// we use - 1 because lists start at 0
const el = e.srcElement.classList.value - 1;
sections.forEach((section, index) => {
if (index === el) {
section.classList.toggle('minus')
} else if (!section.classList.contains('minus')) {
section.classList.add('minus')
}
})
}
Working example
https://codepen.io/anon/pen/KoWgwm
Stuff used
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

How to replace two class attribute in html content?

In my project, I fetch html content from DB with ajax, and these content will appear in web in div with id of timeTagDiv.
If My name is John, it should appears:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
If my name is snow, it should appears:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
Here is my ajax code:
var stChr="John";
var stTrnStr="translateto";
$.ajax({
......
success:function(data)
{
var $myHtml = $(data.stPrc);
$myHtml.find("label").filter(function(){
return $(this).text()===stChr;
}).parent().attr("class", "rightd");
//$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().attr('class','rightd');
$('#timeTagDiv').html($myHtml);
}
});
Here is the content of data.stPrc from DB:
<div class="leftd">
<label>17:05:31</label>
<label>John</label>
<label> translateto</label>
<label>maintanceGroup</label>
</div>
<div class="leftd">
<div class="speech left" >letMnGrpmakeit</div>
</div>
<div class="leftd"><label>17:05:53</label>
<label>snow</label>
<label> acceptSheet</label>
</div>
<div class="leftd">
<label>17:06:04</label>
<label>snow</label>
<label> translateto</label>
<label>leadGrp</label>
</div>
<div class="leftd">
<div class="speech left" >leadercheckit</div>
</div>
When the context of label is John, the attribute class of parent div changed to rightd. Here is the code working successfully:
$myHtml.find("label").filter(function(){
return $(this).text()===stChr;
}).parent().attr("class", "rightd");
And then, the content of letMnGrpmakeit belongs to John should at the right side. So the next two divs class should be set class="rightd" and class="speech right".
In my example, before:
<div class="leftd">
<div class="speech left" >letMnGrpmakeit</div>
</div>
after replace:
<div class="rightd">
<div class="speech right" >letMnGrpmakeit</div>
</div>
I use :
$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().attr('class','rightd');
$myHtml.find('div:contains('+stChr+' '+stTrnStr+')').next().next().attr('class','speech right');
But unfortunately, they both worked fail.
I have tried one condition:
$myHtml.find('label:contains('+stTrnStr+')').parent().next().attr('class','rightd');
It works, but it appears like:
17:05:31 John translatetomaintanceGroup
letMnGrpmakeit
17:05:53 snow acceptSheet
17:06:04 snow translatetoleadGrp
leadercheckit
"leadercheckit" should under "17:06:04 snow translatetoleadGrp", because it belongs to snow.
I have no idea about this. The key to change two div class are two conditions.
Who can help me?
I'm not sure I understand everything correctly because of wording and grammar, but I would suggest using addClass('className') and removeClass('className') instead. This way if your element has more than one class, it will only remove the desired class. By using .attr('class', 'className'), you're replacing everything. If you wish to add multiple classes, just use .addClass('class-1 class-2')
Use these:
$myHtml.find('label:contains('+stChr+')').next('label:contains('+stTrnStr+')').parent().next().attr('class','rightd');
$myHtml.find('label:contains('+stChr+')').next('label:contains('+stTrnStr+')').parent().next().children("div").eq(0).attr('class','speech right');

Get first child ID from an article with just a class name with Jquery

I have my code like this. It is supposed to show like horizontal buttons with dates. When the user clicks on one of that buttons, the box expands itself showing the pictures in it.
I'm trying to get the first child ID of the article clicked with jquery to be able to show the gallery_items with the first child ID without the "_title" at the end. But I get undefined.
My html:
<section id="gallery">
<article class="gallery_date">
<div id="1389848400_title">16-01-2014</div>
<div class="gallery_items" id="1389848400">
261689_10150238069156283_4353481_n.jpg<br>
IMG_4667.jpg<br>
millenium2.png<br>
</div>
</article>
<article class="gallery_date">
<div id="1389762000_title">15-01-2014</div>
<div class="gallery_items" id="1389762000">
IMG_4661.jpg<br>
</div>
</article>
<article class="gallery_date">
<div id="1389675600_title">14-01-2014</div>
<div class="gallery_items" id="1389675600">
bcn.png<br>
logoenmedio.png<br>
</div>
</article>
</section>
My Jquery:
$().ready(function() {
$(".gallery_date").click(function(event) {
console.log($(".gallery_date:first-child").attr("id"));
});
});
Thanks
"I'm trying to get the first child ID of the article clicked with jquery to be able to show the gallery_items with the first child ID without the "_title" at the end."
Do this:
$(this).children().first().prop("id").split("_")[0];
Or without jQuery so it's not so verbose:
this.children[0].id.split("_")[0];
But if that's the only need for the ID, then you could just select the element with .children() by its class:
$(this).children(".gallery_items")
the first child ID without the "_title".
You can use .replace() to remove '_title' or you can use .split()
$(document).ready(function() {
$(".gallery_date").click(function(event) {
var id = $(this).children().first().attr("id")
console.log(id.replace('_title',''));
console.log(id.split("_")[0]);
});
});
Try this:
$(document).ready(function() {
$(".gallery_date").click(function(event) {
console.log($(this).find('.gallery_items:first-child').attr("id"));
});
});
$(".gallery_date").click(function(event) {
console.log($(this).children().first().attr("id"));
});
If your html is structured the way it is, you can also just use the .next() method to get the gallery_items div, like this, so you don't have to worry about getting IDs and retrieving the DOM elements again:
$(document).ready(function() {
$(".gallery_date").click(function() {
$(this).next(".gallery_items").slideDown();
});
});

animate show/hide from css class

I'm new to JavaScript and jQuery so please be gentle with me. I'm trying to animate a show/hide of several divs based on if it has a certain class or not.
Basically, I'm creating a site for a photographer and have a portfolio section with a list of filters along the top, each div has a class of "portfolio-items" as well as additional classes for all the categories it's in, so family / wedding / kids / couples. any image can have multiple classes on it.
What I want to do is click on the family link and it hides anything that doesn't have the family class on it. If I then click on wedding it closes anything that's currently open that doesn't have the wedding class on it and opens anything thats currently closed that does have the wedding class on it.
I currently have it working with the code below but this simply closes everything and then opens the ones that have the class required. Plus I don't know how to add an animate to it.
function portfolioItems(filter) {
$(".portfolio-items").hide();
$("."+filter).show(); }
function initEventHandlers () {
$(".port-all").click(function () {
$(".portfolio-items").show();
return false;
})
$(".port-wedding").click(function () {
portfolioItems("wedding");
return false;
})
$(".port-family").click(function () {
portfolioItems("family");
return false;
})
$(".port-kids").click(function () {
portfolioItems("kids");
return false;
})
$(".port-couples").click(function () {
portfolioItems("couples");
return false;
}) }
The HTML is...
<div class="portfolio-container">
<div class="portfolio-links">
<img alt="All" class="port-all" src="images/port-all.png" />
<img alt="family" class="port-family" src="images/port-family.png" />
<img alt="wedding" class="port-wedding" src="images/port-wedding.png" />
<img alt="couples" class="port-couples" src="images/port-couples.png" />
<img alt="kids" class="port-kids" src="images/port-kids.png" />
</div>
<div class="portfolio">
<div class="portfolio-items wedding couples family"></div>
<div class="portfolio-items kids"></div>
<div class="portfolio-items wedding kids family"></div>
<div class="portfolio-items couples"></div>
<div class="portfolio-items couples kids family"></div>
<div class="portfolio-items wedding"></div>
</div>
</div>
First of all you may use not selectors(look here!) to avoid hiding all your photos. Just assign two classes to your blocks with photos. Something like this
<div class="portfolio-items wedding"></div>
<div class="portfolio-items family"></div>
<div class="portfolio-items kids"></div>
And then you can rewrite your portfolioItems function in this way
function portfolioItems(filter) {
$(".portfolio-items:not(."+filter+")").hide();
}
Secondly you may create one generic function for hiding some category, but not duplicating the same code by several times.
You can try this:
function portfolioItems(filter) {
$(".portfolio-items.not("+filter+")").fadeOut();
$("."+filter).fadeIn();
}
Here's an approach I've found useful for filtering via CSS. I like to use the data attribute on links to specify a filter. To start, set up a navigation with some links and a portfolio with some images or divs:
<!-- set up some navigation -->
<nav>
All Photos
Family Photos
Art Photos
Wombat Photos
</nav>
<!-- set up a portfolio -->
<div class="portfolio">
<div class="family item">Some family image or something</div>
<div class="art item"> Some art image or something</div>
<div class="wombats item">Some wombat image or something</div>
<div class="wombats item">Some wombat image or something</div>
<div class="art item"> Some art image or something</div>
</div>
Notice how each of the a tags has the class name you'd want to use as a filter as a data-filter attribute. You can specify multiple classes in here and it'll work just the same. For instance ".wombat.family" would let you use a DOUBLE filter in your portfolio.
Here's a script that will help you get set up to filter:
//on document ready
$(document).ready(function(){
//when you click <a> tag in the <nav>
$("nav a").click(function(e){
//if the <a> has a data-filter attribute
if($(this).attr("data-filter")){
//show all the .items with the class in the data-filter attribute
$(".portfolio .item"+$(this).attr("data-filter")).show(300);
//hide all the .items that do not have that class
$(".portfolio .item:not("+$(this).attr("data-filter")+")").hide(300);
}else{
//if there's no data-filter attribute, show all the images
$(".portfolio .item").show(300);
}
});
});
For this one, I'm simply using a time in the show() and hide() functions, but fadeIn() fadeOut() might work for you as well.
To enable the "all" filter, I simply didn't write a data-filter attribute for that particular a tag and made sure JS knew what to do (check the if/else).
The important thing to remember is the link between the class used on the portfolio item and the data-filter attribute. Pretty simple to get started, though I'm sure it'll get a little more complicated before you get finished :)
Here's a jsfiddle to play around: http://jsfiddle.net/w4VWm/
Good luck!
Hide all, add the new classname to a filter string then show by the filter string
http://jsfiddle.net/uhCY5/3/
var filters = "";
function portfolioItems(filter) {
filters += '.' + filter
$(".portfolio-items").hide();
$(filters).show();
$("#filter").text(filters)
}
function initEventHandlers() {
$(".port-all").click(function () {
filters = "";
$(".portfolio-items").show();
return false;
})
// the rest is the same
}
Not sure exactly what kind of transition you want, but this will do a fade in/out with very little jquery:
please note, you may be able to remove some of the stuff in the divs, but i didn't know what you needed for other things on the page
the fiddle: http://jsfiddle.net/Z5uXP/
<div class="portfolio-container">
<div class="portfolio-links">
<img alt="All" class="port-all" src="images/port-all.png" />
<img alt="family" class="port-family" src="images/port-family.png" />
<img alt="wedding" class="port-wedding" src="images/port-wedding.png" />
<img alt="couples" class="port-couples" src="images/port-couples.png" />
<img alt="kids" class="port-kids" src="images/port-kids.png" />
</div>
<div class="portfolio">
<div class="portfolio-items wedding couples family"></div>
<div class="portfolio-items kids"></div>
<div class="portfolio-items wedding kids family"></div>
<div class="portfolio-items couples"></div>
<div class="portfolio-items couples kids family"></div>
<div class="portfolio-items wedding"></div>
</div>
</div>
<script>
$(document).ready(function(){
var $container = $("div.portfolio-container"),
$portfolio = $container.find("div.portfolio");
$container
.on("click", ".portfolio-links a", function(event){
var $obj = $(this);
event.preventDefault();
$portfolio
.fadeOut()
.queue(function(next){
$($(this)[0]).css("color", "red")
.removeClass("family wedding couples kids")
.addClass($($obj[0]).data("type"));
next();
})
.fadeIn();
});
});
</script>
<style>
.portfolio .portfolio-items{
display: none;
}
.portfolio.all .portfolio-items,
.portfolio.family .portfolio-items.family,
.portfolio.wedding .portfolio-items.wedding,
.portfolio.couples .portfolio-items.couples,
.portfolio.kids .portfolio-items.kids{
display: block;
}
</style>

How to stay within a 'instance' using JQuery

I'm currently learning JavaScript/JQuery, but have an issue at work that I'm running into.
I've assigned a class of 'question' to an<a>tag, and 'answer' to a<div>. When a user clicks on the question, the answer will slide down. However, the problem I'm running into is that when they click on a <a href="#" class="question">, all of the <div class="answer">'s are displayed.
How can I make it so that only one .answer for it's parent .question is displayed when clicked?
Here is my HTML:
<li class="question">Question 1
<div class="answer"><p>This is answer for question 1</p></div></li>
<li class="question">Question 2
<div class="answer"><p>This is answer for question 2</p></div></li>
Here is my jquery:
<script>
jQuery(document).ready(function ($) {
$('div.answer').hide();
$('li.question').click(function() {
$('div.answer').slideDown('fast');
return false;
});
});
</script>
and the site is: http://topactioninvestments.com/faq/
Thanks!
$('li.question').click(function(e) {
$(this).find('div.answer').slideToggle('fast');
e.preventDefault();
});
Give every answer element an unique id attribute and add a data-answer attribute to the the the question that references the unique question.
The do the following.
$('li.question').click(function(e) {
$($(this).data("answer")).show();
});
To clarify with the relevant html.
<li class="question" data-answer="#answer-42">...</li>
<div class="answer id="answer-42">....</div>
What you typically want to do is have each unit within a container element. An example would be a div or other tag. Say your HTML looked like this:
<div class="qa">
<div class="question">What is 2+2?</div>
<div class="answer">4</div>
</div>
Then you could do:
$('.question').click(function(event) {
var target = $(event.target);
target
.closest('.qa')
.find('.answer')
.show();
});
Your markup for each question and answer looks like this:
<li>
<a><strong>Why do you not just sell these option contracts?</strong></a>
<div class="answer"><p>This is a test</p></div>
</li>
For this markup, this JavaScript would work:
$('li').on('click', function(event) {
$(this).find('.answer').show();
});
Demo: jsfiddle

Categories