How to stay within a 'instance' using JQuery - javascript

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

Related

jQuery .slideToggle() to also close other tabs

I have two sections, each with 3 divs, opening on slideToggle. How can I close the other 2 divs in each section when 1 is open?
https://jsfiddle.net/koteva/mdx20uqe/2/
<div id="stage1">
<h2 id="location-1">Location</h2>
<div id="location-1t">grjryjj</div>
<h2 id="jersey-1">JERSEY </h2>
<div id="jersey-1t" style="display: none;"> ighlgkiuluil </div>
<h2 id="details-1">details</h2>
<div id="details-1t" style="display: none;">fykyuk </div>
</div>
<div id="stage2">
<h2 id="location-2">Location2</h2>
<div id="location-2t">grjryjj</div>
<h2 id="jersey-2">JERSEY2 </h2>
<div id="jersey-2t" style="display: none;"> ighlgkiuluil </div>
<h2 id="details-2">details2</h2>
<div id="details-2t" style="display: none;">fykyuk </div>
</div>
With your jsFiddle, you could replace all your js code with
$('h2').click(function(event){
var $this = $(event.target),
id = $this.attr('id');
if($('#'+id+'t').is(':visible')){ // To not slide up and down if clicking an already open element.
$this.parent().children('div').slideUp();
} else {
$this.parent().children('div').slideUp();
$('#'+id+'t').slideToggle();
}
});
as seen in this jsFiddle. This hides the content inside the same stage when you click a header, assuming you follow the same naming convention throughout your entire html code.
I would however recommend, if you can, to perhaps clean up your html a little.
Look at this jsFiddle for an example.
Unless your code has to have your current structure, I would recommend refactoring it into using similar classes and as such be able to write cleaner code.
$('.header').click(function(event){
var $this = $(event.target);
$this.siblings().slideToggle();
$this.parent().siblings().children('.content').slideUp();
});
Would with the structure in the jsFiddle html provide you with the functionality you want.
If you want to do it in simple way. You can do it as follows. its just one function written. But it is simple and line of code will be increased
$( "#details-2" ).click(function() {
$( "#location-2t").hide( "slow");
$( "#jersey-2t").hide( "slow");
$("#details-2t").show("slow");
});
For more complex div structure and the Ids are in the same format as you have specified in your sample code following code will be very useful.
<script>
$(document).ready(function(){
$("div h2").click(
function() {
var thisId = $(this).attr("id");
$("#"+thisId+"t").show("slow");
$(this).siblings("div").not($("#"+thisId+"t")).hide("slow");
});
});
</script>

Only has class show, other divs hide via jQuery

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.

If href equals id of another div do function

I have a hidden div with the details of a thumbnail that is visible on the page. When you click on the thumbnail, it should fadein or slideup the div with details.
I have set with jquery incremented ID's to each ".portfolio-item-details" to identify each one and then have set with jquery the same ID's to the href of the thumbnail.
<section id="portfolio1" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio1" title="">
<img src="thumbnail.jpg">
</a>
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
Since this is done dynamically, how can I with jquery fadeIn or slideUp the ".portfolio-item-details" if the href is equal to the ID. Basically thumbnail with "#portfolio1" should slide up the div with "#portfolio1" on click.
This is my jquery code which to add the IDs and HREF is working perfectly but not working to slideUp or fadeIn the div with the same ID.
$(document).ready(function () {
var i=0;
$(".portfolio-item-details").each(function(){
i++;
var newID="portfolio"+i;
$(this).attr("id",newID);
$(this).val(i);
});
var i=0;
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="#portfolio"+i;
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
});
});
SOLUTION
Thanks to Austin's code, I was able to modify it to work with mine.
Check here: http://jsfiddle.net/jdoimeadios23/xpsrLyLz/
You want something like this?
HTML
<div class="image" value="1">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio1" class="details">details</div>
<div class="image" value="2">
<img src="thumbnail.jpg" />
</div>
<div id="portfolio2" class="details">more details</div>
JS
$(document).ready(function () {
$('.details').fadeOut(1);
$(".image").click(function () {
var num = $(this).attr("value");
$("#portfolio"+num).fadeIn(1000);
});
});
JSFiddle Demo
You don't even need to bother with ID's so long as the next div below each image is it's details.
The problem is in this block
if ($(".portfolio-item-details").attr("id") == "newReadMoreHREF") {
$(this).fadeIn();
}
Because you're having two errors, the first one is that newReadMoreHREF is a variable, not a string in your HTML or a value to any variable and so on.
Second thing is, that in the variable declaration you're using "#portfolio"+i;, which would be good if you were about to select an element. But using it in the jQuery iif statement with .attr('id') will again cause a havoc.
The thing that you need is something like this
$(".open-portfolio-item-details").each(function(){
i++;
var newReadMoreHREF="portfolio"+i; // removed #
$(this).attr("href",newReadMoreHREF);
$(this).val(i);
if ($(".portfolio-item-details a").attr("id") == newReadMoreHREF) {
// you need to access the hyperlink in the element, not
// the element itself. this portfolio1 ID is of a hyperlink
// again here, this is referencing the main iterator.
$(this).fadeIn();
// are you sure you want to fade the .open-portfolio-item-details?
}
});
Removed the hash sign and then called the variable value to check against. It would execute to be true if the condition is true.
Try this:
HTML:
content
<section id="portfolio2" class="portfolio-item-details hidden">content</section>
<a class="open-portfolio-item-details" href="#portfolio2" title="">
<img src="thumbnail.jpg">
</a>
<div id="portfolio1" class="portfolio" hidden>Portfolio 1</div>
<div id="portfolio2" class="portfolio" hidden>Portfolio 2</div>
Jquery:
$('a.open-portfolio-item-details').on('click', function (e) {
e.preventDefault();
var id = $(this).attr('href');
$('.portfolio').hide();
$('.portfolio' + id).fadeIn();
});
Couldn't get the fiddle link for some reason.
Edit:
I don't know the name of the class that shows the content you want displayed, so as an example I'm using portfolio. Try putting this code into a fiddle

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();
});
});

how can I remove the subnavigation overlap?

I am trying to create a sub navigation. Right now I have two subnav. When i hover over the first item on the main menu the corresponding submenu appears. But when I hover over the second item the second sub nav appears OVER the first one. How can I write the code so that this does not happen?
url: http://arabic001.com
$(document).ready(function() {
$('#arbNavText01').mouseover(function() {
$('#subNav01').show('slow');
});
$('#subNav01').mouseleave(function() {
$('#subNav01').hide('slow');
});
$('#arbNavText02').mouseover(function() {
$('#subNav02').show('slow');
});
$('#subNav02').mouseleave(function() {
$('#subNav02').hide('slow');
});
})
I just tried the below suggestion from Scott and I am not able to show and hide the submenu on hover. Any ideas of how to solve this problem? Here are my new codes:
html
<div id="menu01" class="menu_item">
<div id="engNavText01">Alphabet</div>
<div id="arbNavText01">الأحرف</div>
<div id="subNav01" style="display:none;">
<a href="colors" class="subNav">
<span style="font-size:26px; cursor:pointer;">قراءة</span</a>
<br>reading<br><br>
</div>
</div>
<div id="menu02" class="menu_item">
<div id="engNavText02">Numbers</div>
<div id="arbNavText02">الأحرف</div>
<div id="subNav02" style="display: none; ">
<a href="colors" class="subNav">
<span style="font-size:26px; cursor:pointer;">قراءة</span</a>
<br>reading<br><br>
</div>
</div>
and the JS
$(document).ready(function() {
$('.menu_item').children().hover(
function(){
$subNav = $(this).parents('menu_item').children("div[id^='subNav'");
if ($subNav.css('display', 'none')){
$subNav.show('slow');
}
},
function(){
$(this).parents('menu_item').children("div[id^='subNav'").hide('slow');
});
})
You've created a mouseleave event, but you've only attached it to the submenu. So in order to make a menu disappear, the user will have to hover over the submenu and then move out. You could achieve what you want by hiding other submenus before opening a new one. So keeping your mouseleave events as you have them, you could modify your 2 mouseover events to this:
$('#arbNavText01').mouseover(function() {
$('#subNav02').hide('slow');
$('#subNav01').show('slow');
});
$('#arbNavText02').mouseover(function() {
$('#subNav01').hide('slow');
$('#subNav02').show('slow');
});
Edit for comment:
I was thinking about that when I went and looked at your page originally. I think if you used a slightly different structure in your html this could be done. Right now your menu divs aren't clearly structurally related to each other so maybe add a div that can contain the 3 elements associated with each menu item.
I'm going to spit ball an idea, it may not even work let alone be the best way.
<div id="menu01" class="menu_item">
<div id="engNavText01">Alphabet</div>
<div id="arbNavText01">الأحرف</div>
<div id="subNav01" style="display: none; ">
<span style="font-size:26px; cursor:pointer;">قراءة</span
<br>reading<br><br>
</div>
</div>
<div id="menu02" class="menu_item">...
Edited JS, I think now it could work
$('.menu_item').hover(
function(){
$subNav = $(this).children("div[id^='subNav']");
if ($subNav.css('display', 'none')){
$subNav.show('slow');
}
},
function(){
$(this).children("div[id^='subNav']").hide('slow');
}
);
Was trying it out with a JSFiddle, seems alright there. Might need some modification for your uses.

Categories