jQuery to open independently content of each button with the same class - javascript

I don't think my question is difficult but I'm just a newbie in jQuery and this forum so hope that you can help me with this problem. I just want to open seperately the content of two divs by two button with the same class name and for easier to understand I will show my code snippet first:
<div id="CNN">
<div id="article1">
<div class="content">
My content of CNN goes here
</div>
<div class="more">
My button goes here
</div>
</div>
</div>
<div id="Bloomberg">
<div id="article1">
<div class="content">
My content of bloomberg goes here
</div>
<div class="more">
My button goes here
</div>
</div>
</div>
And here is my current jQuery code which is not working:
$(document).ready(function() {
$("div.more").each(function() {
$(this).click(function() {
var target = $(this).parent().next(".content");
$(target).slideDown("slow");
});
});
});
Here I want to click more button and it will show only the content belongs to it. You are free not to follow my current code :). So that's all of my question, hope you all can help me to improve my programming skill and thanks you so much in advanced!

$(document).ready(function() {
$("div.more").click(function(){
$(this).parent().find("div.content").slideDown("slow");
});
});
Should do the trick

Try this:
$(document).ready(function() {
$("div.more").click(function() {
var target = $(this).parent().find(".content");
target.slideDown("slow");
});
});
Example Fiddle

Try this:
$("div.more").click(function() {
$(this).prev().slideDown("slow");
});

Related

jQuery FAQ Accordion only open one at a time

I have a page on a site that has multiple FAQ questions where when you click the " + " the answer slideToggle's. I'm having an issue where on click all of the answers for all questions open, and I want to be able to toggle one at a time.
Is there a way I can do this using "parent" "child" selectors in jQuery?
HTML:
<div class="main-slide">
<div class="main-slide-title">
<p>One-time Close Purchase/Construction Loans</p>
</div>
<div class="main-slide-plus">
<p>+</p>
</div>
</div>
<div class="sub-slide default-hidden">
<ul>
<li>Finance the construction</li>
<li>Purchase of lot</li>
<li>Permanent loan</li>
<li>FHA, and VA are available</li>
</ul>
</div>
</div>
jQuery:
$(".main-slide-plus").click(function () {
$(".sub-slide").slideToggle(500);
});
Yes from the HTML piece you provided, you can get the parent main-slide and then toggle the sibling with class sub-slide
So something like
$(".main-slide-plus").click(function () {
$(this).parents(".main-slide").sibilings(".sub-slide").slideToggle(500);
});
if this is the structure you have repeating for the accordion, you will need to go to the parent, then find the next .subslide element. Along the lines of the following:
$(".main-slide-plus").click(function () {
$(this).parent().next(".sub-slide").slideToggle(500);
});

$().next() returning the same element multiple times

I tried to name the title as best I could. A little difficult for me to explain.
I'm having an issue with some code I'm writing (which runs in a widget on my wordpress site.) What I've written here emulates this issue. Just fyi I'm very new to jquery, JS, etc.
What I'm trying to do is set the variable "thumb" to the element after "widget-code". It works, however it's only finding that element ("thumb-class") in "wordpress-post1"
The console output is:
wordpress-post1
wordpress-post1
wordpress-post1
But it should be:
wordpress-post1
wordpress-post2
wordpress-post3
This is the actual code
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
I'm going to try and clarify a little more:
This code is placed in an html widget which the wordpress theme I'm using provides. It hooks into each post. This is the only place I can put code, and this is the only code I've written. (I haven't altered the theme's files in any way.)
I have no control over the name of the classes or IDs. And they're dynamic. An unlimited number of posts could exist. Therefore I can't hardcode anything.
In order for this code to work correctly it'll need to find the sibling of the "widget-code" element in only the post it's running from.
This is the link to the code on JSFiddle: http://jsfiddle.net/pattnvy3/
Would appreciate any help on the matter.
If you want a nasty hack, try
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var c = window['widget-code-counter'] || 0;
window['widget-code-counter'] = ++c;
var className = 'wordpress-post' + c;
console.log(className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
Demo: Fiddle
It will give the container class wordpress-post1, then you can use it to find any of the descendant element.
As per the immediate comments, it is invalid markup to use an id for multiple elements. That said, changing your id to a class such that:
<div class="wordpress-post[some-number-here]">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
would allow you to to a jQuery selector like so:
$('.widget-code').each(function (){
var thumb = $(this).next();
console.log(thumb[0].parentElement.className);
});
However, if I may make a recommendation, I would say that you tag each of your wordpress-post divs with the class "wordpress-post" and then have a more specific id which is the value you want to print.
Then it would look like this:
<div id="wordpress-post[some-number-here]" class="wordpress-post">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
and your javascript like this (with jQuery):
$('.widget-code').each(function (){
var post = $(this).closest('.wordpress-post');
console.log(post.attr('id'));
});
or even simpler:
$('.wordpress-post').each(function (){
console.log($(this).attr('id'));
});
depending on the needs you have. If you have any questions as to what you need, feel free to comment and I will get back to you as soon as I can.
A pure javascript method:
This is just a workaround since you have no control over ids or classes, this will target all div elements on the page, loop through them and search for any that contains wordpress-post in the class name.
window.onload=function(){
var posts=document.getElementsByTagName('div');
for(var i=0; i<posts.length; i++){
if(posts[i].className.indexOf("wordpress-post")> -1){
console.log(posts[i].className);
//Snippet Use
alert(posts[i].className);
}
}}
<div class="wordpress-post1">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post2">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post3">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
If you have any questions, please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
This can help if you want to have multiple IDs:
$(document).ready(function(){
$("[id^=widget-code]").each(function(){
console.log(this.parentElement.className);
});
});
But, still multiple same Ids are not recommended.
FIDDLE
Update: Declare a global variable var i=0; and keep increment it like :
<div class="wordpress-post1">
<div id="widget-code">
<script>
var i=0;
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
DEMO

jquery hide rows of divs between two divs when having certain class

<div id="CntWrapper_CntMain_ssm_ctl00_ctl01" class="matrix">
<div class="CollapseGroup1"></div>
<div class="row">
<div class="cell_24"> </div>
</div>
<div class="row">
<div class="cell_24">
<span class="label-passive">text</span>
</div>
</div>
<div class="CollapseGroupClose1"></div>
</div>
I'm trying to manipulate above HTML code sample. It's a simplified version the actual HTML code.
<script type="text/javascript">
$(document).ready(function() {
$('.CollapseGroup1').nextUntil('.CollapseGroupClose1',').css( "display", "none" );
});
</script>
This script hides all the div with class 'row' between the two divs called collapsegroup and collapsegroupclose.
However, I only want to hide the div elements with class 'Row' when any of these rows contain at least one span with class 'label-passive'.
<script type="text/javascript">
$(document).ready(function() {
$('.CollapseGroup1').nextUntil('.CollapseGroupClose1','div[.label-passive]').css( "display", "none" );
});
</script>
Just simply hiding any row div when there is a span with label-passive is not good enough. There can be rows with 'label-passive' span classes outside these collapsegroup divs that I don't want to hide.
I want to hide all rows between two collapsegroup tags, even when just one of these rows actually has a child span element with class 'label-passive'.
So, after reading your question once.. Twice.. Trice.. I think you want this:
(pro-tip: try to keep your questions as simple as possible, using pseudo-code if you must)
$('.label-passive').parents('._row').hide();
If this isn't completely what you wanted, leave a comment and I'll try to improve the answer.
Edit: Improved answer as OP improved his question:
Maybe this will help you further then:
$('.CollapseGroup1').each(function() {
if ($(this).find(".label-passive").length != 0)
$(this).hide();
});
You can simply try this:
$('div.row:has(.label-passive)').hide();
Try closest():
$('span.label-passive').closest('div.row').hide();
$(function() {
$('span.label-passive').closest('div.row').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="CntWrapper_CntMain_ssm_ctl00_ctl01" class="matrix">
<div class="CollapseGroup1"></div>
<div class="row">
<div class="cell_24"> </div>
</div>
<div class="row">
<div class="cell_24">
<span class="label-passive">text</span>
</div>
</div>
<div class="CollapseGroupClose1"></div>
</div>

Javascript and jQuery to make divs into a tab based content page

I recently had a 30 min test for a job application using only Javascript with jQuery. Didn't have to be styled well or anything. I created a very basic "30 min" page with Javascript and jQuery which I thought was "ok".. I just wanted to get some feedback if there was a more efficient/better way of doing this? as it turned out, I didn't get the job.. always learning, and also the job was quite a way from where I live.
Anyway, the original HTML page given was as follows, and after that is my humble attempt to turn the basic HTML into a tab based content page - again within 30 mins.
<html>
<head>
<!-- stylesheet, javascript, etc. here -->
</head>
<body>
<h1>My Page</h1>
<h2 class="subheading">The first section</h2>
<div class="content">
<p>Lorem ipsum...</p>
</div>
<h2 class="subheading">The second section</h2>
<div class="content">
<img src="/some_image" alt="Image" title="Image"></img>
<p>Some other text</p>
</div>
<h2 class="subheading">The third section</h2>
<div class="content">
And some more text here
</div>
<div class="footer">
This is at the foot of the page
</div>
</body>
</html>
Ok, so my humble attempt is as follows:
<html>
<head>
<title>Test JS page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<style type="text/css">
#tabs
{
width:457px;
height:60px;
}
#tab1, #tab2, #tab3
{
width:150px;
border:1px solid #ccc;
}
#tab1
{
float:left;
}
#tab3, #tab2
{
float:right;
}
#tab2_content, #tab3_content
{
display:none;
}
.clear
{
clear:both;
}
#content
{
height:300px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#tab1_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab1_content').show();
});
$('#tab2_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab2_content').show();
});
$('#tab3_link').click(function (e) {
e.preventDefault();
clearContent();
$('#tab3_content').show();
});
});
function clearContent() {
$("div[id*='_content']").each(function() {
$(this).hide();
});
}
</script>
</head>
<body>
<h1>My Page</h1>
<div id="tabs">
<div id="tab1"><a id="tab1_link" class="subheading">The first section</a></div>
<div id="tab2"><a id="tab2_link" class="subheading">The second section</a></div>
<div id="tab3"><a id="tab3_link" class="subheading">The third section</a></div>
</div>
<div class="clear">
</div>
<div id="content">
<div id="tab1_content" class="content">
<p>Lorem ipsum...</p>
</div>
<div id="tab2_content" class="content">
<img src="/some_image" alt="Image" title="Image"></img>
<p>Some other text</p>
</div>
<div id="tab3_content" class="content">
And some more text here
</div>
</div>
<div class="footer">
This is at the foot of the page
</div>
</body>
</html>
So as you can see, not pretty for sure.. the stylesheet was inline as is the script, however this was meant to be a test to show if you knew Javascript/jQuery enough to perform the tasks.. I figured it wasn't great, but not too bad either..
I would be grateful for any feedback on other ways to achieve the desired result.. again it doesn't have to be pretty, just functional.. and of course all within 30 mins..
Thanks!
<div id="tabs">
<ul>
<li>The First Section</li>
<li>The Second Section</li>
<li>The Third Section</li>
</ul>
<div id="tabs-1" class="content">
<p>Lorem ipsum...</p>
</div>
<div id="tabs-2" class="content">
<img src="/some_image" alt="Image" title="Image"></img>
</div>
<div id="tabs-3" class="content">
<p>Some other text</p>
</div>
</div>
<script>
$(function() {
$("#tabs").tabs();
});
</script>
http://jqueryui.com/demos/tabs/
Without knowing something about the company you were taking the test for its hard to say what they were looking for.
In general employers are not looking for perfect code but how you approach the problem. For example you could say that they were looking to see if you would follow their instructions blindly or stick to convention and good practices of adding external style/script references or just clean, standard compliant, concise code.
I am a complete novice so please don't take anything I say too seriously but I would of attempted to create some reusable concise code which would/could be reused and expanded very quickly and easily while being maintenance friendly (Just because its a text doesn't mean that you can forget about these things).
Just doing this very rough and off the top of my head but something like this:
$('#tab-menu').click(function(e) {
e.preventDefault();
clearContent();
$(this).show();
});
If it was for a company that were involved with mobile devices you would probably want to bind the events so you get the same functionality.
Something that I have always done is provided an assumptions document even just if its in notepad. Its always looked upon positively as it shows you are stopping and thinking about what you have to do instead of going gun ho.
Overall I think you did a good job! You have a great attitude and just learn from experiences like these, improve and get better! Today's juniors will be tomorrows experts! if we work hard enough
you don't need jQuery UI for this.
demo http://jsbin.com/atogil/2/edit
HTML
<div class="tabs">
<nav class="tab-btns">
tab btn 1
tab btn 2
tab btn 3
tab btn 4
</nav>
<div class="tab-contents">
<div id="tab1">tab content 1</div>
<div id="tab2">tab content 2</div>
<div id="tab3">tab content 3</div>
<div id="tab4">tab content 4</div>
</div>
</div>
JS
$.fn.myTabs = function(settings){
return this.each(function() {
/*
save cached version of the first elements inside the containers.
by calling the first elements of each container you are not limitng
the plugin user to any specific class or elememt.
*/
var btns = $(settings.nav, this).children(),
tabs = $(settings.tabs, this).children();
/*
we relying on the order of the elements as the conection between
the buttons and the tabs notice that .each() get the index of the btn..
we are useinf it to find the current tab.
*/
btns.each(function(index){
var btn = $(this),
tab = tabs.eq(index);
btn.click(function (e){
/* prevent unnesscry work by checking
if the button clicked is already active */
if(btn.is('.active')) return false;
/* notice that first filter to find the last 'active'
button before we remove the 'active' class otherwise it
remove the class for every button.
unnesscry work prevented again */
btns.filter('.active').removeClass('active');
/* hide previus tab.. */
tabs.filter(':visible').hide();
btn.addClass('active');
tab.show();
return false;
});
});
// emulate click on the first tab button;
btns.first().click();
});
};
and call your script like this;
$(function() {
$('.tabs').myTabs({
// container of navigation inside '.tabs'
nav : '.tab-btns',
// container of contents inside '.tabs'
tabs : '.tab-contents'
});
});

jQuery - how to run one event while delaying another?

I'm a bit of a jQuery newbie, so forgive me if this seems a bit simple! I am setting up a sliding header system, which works very much like an accordion menu, however the links to open and close the elements are in a different part of the HTML, so all the accordion tutorials I found didn't work.
I have got this so far: HTML:
<div class="drawer" id="drawer_about"></div>
<div class="drawer" id="drawer_contact"></div>
<div class="drawer" id="drawer_hire"></div>
<div class="drawer" id="drawer_social"></div>
...
<ul class="navigation">
<li><span>About Me</span></li>
<li><span>Get In Touch</span></li>
<li><span>Hire Me</span></li>
<li><span>Social Networks</span></li>
</ul>
And jQuery:
$(document).ready(function(){
$("#drawer_about").hide();
$("#drawer_contact").hide();
$("#drawer_hire").hide();
$("#drawer_social").hide();
lastBlock = ("#drawer_hire");
$('.show_hide_about').click(function(){
$("#drawer_about").slideToggle(700);
$(lastBlock).hide(700);
lastBlock = ("#drawer_about");
});
$('.show_hide_contact').click(function(){
$("#drawer_contact").slideToggle(700);
$(lastBlock).hide(700);
lastBlock = ("#drawer_contact");
});
$('.show_hide_hire').click(function(){
$("#drawer_hire").slideToggle(700);
$(lastBlock).hide(700);
lastBlock = ("#drawer_hire");
});
$('.show_hide_social').click(function(){
$("#drawer_social").slideToggle(700);
$(lastBlock).hide(700);
lastBlock = ("#drawer_social");
});
});
Am I going OTT here? is there a simpler way to do this?
The main problem I'm having is it all works, however if the ABOUT ME panel is open and the user clicks the HIRE ME link, I get a weird effect. What I'd want in this situation is for the ABOUT ME panel to fold up, then the HIRE ME panel to fold down.
Hope that makes sense, thanks folks,
Alex
I'd set up the links like this: asdf
Then you all you need is:
$('.show').click(function(ev) {
var $visibleDrawer = $('.drawer:visible').eq(0); // make sure to get only one (or 0) drawer
// set currentSection to the drawer's id or empty if no drawer was found
var currentSection = $visibleDrawer.length?$visibleDrawer.attr('id').replace('drawer_',''):'';
$('.drawer').slideUp(700);
$('a.show').removeClass('active'); // reset all link classes
(function(clickedSection, $link){ //<-- pass the active link to have access to it inside the closure
if(currentSection != clickedSection){
$link.addClass('active'); // set active class on clicked link
setTimeout(function() {
$('#drawer_'+clickedSection).slideDown(700);
}, ($visibleDrawer.length?700:0)); // set the timeout to 0 if no drawer visible
}
})($(this).data('section'),$(this)); //<--
ev.preventDefault();
});
using .animate() you can parse a callback function which will be executed at the end of the animation, or you can use .queue() to keep track of the point of execution against and element. Some pseudo code of the first way
$('#foo').animate(function() {
// do stuff with foo
}, duration, easing, function() {
$('#bar').animate(function() {
// do stuff with bar
})
});
Here is a link to how it works on jsFiddle (Note that you should choose framework to be jQuery)
I think this would work with you :
$(document).ready(
function(){
$('.header').click(function(){
//To hide all other contents
$('.content').slideUp('slow');
var num=$(this).attr('id').split('_')[1];
//And show this one ..
$('#content_'+num).slideDown('slow');
});
}
);
HTML should look like this :
<div class="header" id="title_111">Category 1</div>
<div class="content" id="content_111">
</div>
<div class="header" id="title_112">Category 2</div>
<div class="content" id="content_112">
</div>
<div class="header" id="title_113">Category 3</div>
<div class="content" id="content_113">
</div>
<div class="header" id="title_114">Category 4</div>
<div class="content" id="content_114">
</div>
<div class="header" id="title_115">Category 5</div>
<div class="content" id="content_115">
</div>
<div class="header" id="title_116">Category 6</div>
<div class="content" id="content_116">
</div>

Categories

Resources