Add content to sibling div - javascript

In the example below what's the simplest addContent function that will put some content into the child div?
<div>
My Link
<div/>
</div>
Clicking the link should result in:
<div>
My Link
<div>Added Content</div>
</div>

Take a look at next:
$(document).ready(function() {
$(".addContent").click(function(e) {
e.preventDefault();
$(this).next("div").html("<div>Added Content</div>");
});
});
Instead of using an inline function, give your 'add content' links a class, and bind to anchors with that class as in the above example:
<a class="addContent" href="#">My Link</a>
Try a demo here: http://jsfiddle.net/wGz8s/1/

Related

how to select sibling element when click a link?

I have serval link buttons in order to show a div below it.
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<a class="btnComment" onclick="showComment()" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
I want to clink one linkbutton and only show the div element below it. but my js code:
function showComment(){
var isshow=$(this).attr('isshow');
if(isshow=="0"){
this.$(".comment").show();
$(this).attr('isshow',"1");
}
else{
this.$(".comment").hide();
$(this).attr("isshow","0");
}
}
this show all div. and when i use $(this).siblings() or $(this).next(), i got null, i don't know why that not work.
What can i do?
this is not pointing to the element if you run it in an inline event. Try the following:
onclick="showComment(this)"
And:
function showComment(el) {
var isshow=$(el).attr('isshow');
if(isshow=="0"){
$(el).next(".comment").show();
$(el).attr('isshow',"1");
}
else{
$(el).next(".comment").hide();
$(el).attr("isshow","0");
}
}
Or if you use jQuery's click, you can use this to point to the element:
$('.btnComment').click(function(event) {
var isshow=$(this).attr('isshow');
if(isshow=="0"){
$(this).next(".comment").show();
$(this).attr('isshow',"1");
}
else{
$(this).next(".comment").hide();
$(this).attr("isshow","0");
}
});
You should wrap your <a> and <div> inside another <div> to create a more maintainable code. Like this:
<div class="commentContainer">
<a class="btnComment" isshow='0'>{{ post_comments.count }} comment</a>
<div class="comment">
....
</div>
<div>
This parent div serves as the context for your tags. In the future, if you change the position, move <a> after <div>, your code still works fine. And it's even possible for you to to styling as a group just by assigning a class to the container.
Your jquery, here I use jquery event handler instead.
$(".btnComment").click(function () {
var isshow = $(this).attr('isshow');
var parent = $(this).closest(".commentContainer");
if (isshow == "0") {
parent.find(".comment").show();
$(this).attr('isshow', "1");
} else {
parent.find(".comment").hide();
$(this).attr("isshow", "0");
}
}
If you use .next(), it means your code is coupled to the current html.
css
.hide{visibility:hidden;}
.show{visibility:visible;}
jquery
$('.btnComment').click(function(){
$('.btnComment + div').removeClass('show').addClass('hide');
$(this).next().removeClass('hide').addClass('show'); });
html
<a class="btnComment" href="javascript:;"
sshow='0'>click1</a> < div
class="hide">sandy1</div> <a class="btnComment"
href="javascript:;" isshow='0'>click2</a> <div
class="hide">sandy2</div> <a class="btnComment"
href="javascript:;" isshow='0'>click3</a> <div
class="hide">sandy3</div>
On every click of anchor tag respective div will be shown and others will be hidden.
Hope this will help you.

How can I use "div" in Twitter's Popover with multiple buttons?

This solution is ok for one button cases: Is it possible to use a div as content for Twitter's Popover
But in my page I have a bunch of popovers (say 50-100).
So I need to modify this solution.
This wa #jävi's solution:
$(document).ready(function(){
$('.danger').popover({
html : true,
content: function() {
return $('#popover_content_wrapper').html();
}
});
});
Each of my button has its own id.
<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_div1" style="display: none">
<div>This is your div content</div>
</div>
<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_div2" style="display: none">
<div>This is your div content</div>
</div>
So how can I rewrite this javascript code snippet to cover all my buttons?
Just fought with this myself. You need to put the id in the element that triggers the popover. Use a custom data attribute like so (called 'data-id'):
<a class='danger' data-id="popover_div1" data-placement='above' title="Popover Title" href='#'>Click</a>
Then you can modify your javascript slightly to grab the data-id attribute value programmatically:
$(document).ready(function(){
$('.danger').popover({
html : true,
content: function() {
return $($(this).attr('data-id')).html();
}
});
});
If you don't want to pollute your source element with another data-* attribute, here is a simple and generic way to use the data-content attribute as text or CSS selector:
$('[data-toggle="popover"]').popover({
html: true,
content: function() {
var content = $(this).data('content');
try { content = $(content).html() } catch(e) {/* Ignore */}
return content;
}
});
You can now use the data-content attribute with a text value:
<a data-toggle="popover" data-title="Popover Title" data-content="Text from data-content attribute!" class="btn btn-large" href="#">Click to toggle popover</a>
...or use the data-content attribute with a CSS selector value:
<a data-toggle="popover" data-title="Popover Title" data-content="#countdown-popup" class="btn btn-large" href="#">Click to toggle popover</a>
<div id="countdown-popup" class="hide">Text from <code>#countdown-popup</code> element!</div>
You can test this solution here: http://jsfiddle.net/almeidap/eX2qd/
...or here, if you are using Bootstrap 3.0: http://jsfiddle.net/almeidap/UvEQd/ (note the data-content-target attribute name!)
You can do it without additional button attributes like this:
http://jsfiddle.net/isherwood/E5Ly5/
.popper-content {
display: none;
}
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content">My first popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content">My second popover content goes here.</div>
<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content">My third popover content goes here.</div>
$('.popper').popover({
container: 'body',
html: true,
content: function () {
return $(this).next('.pop-content').html();
}
});
Store the id of the div containing the popover html inside the rel attribute of the a element
<a rel="popover_div2" ... >click</a>
And then get the rel of the click anchor inside your click listener (not sure how the popover method stores it, but I'm sure it does):
var myRel = $(this).attr(rel);
return $(myRel).html();
For me it has do be
data-id="#popover_div1"
in the HTML for the button (with a # for addressing the id of the div).

How do I use a function argument for this jquery code, or is there a better solution?

I have about 50 p tags and next to these are again 50 divs. on click of each p tag, its div should be shown and the rest hidden. How do i acheive this. I can use something like below:
$(function() {
$('.p1').click(function(){
$('.div1').show();
$('.div2','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
$('.p2').click(function(){
$('.div2').show();
$('.div1','.div3','.div4','.div5','.div6',.........,'.div50').hide()
})
//////////////
//////
})
but as you see that this is not an effiecient solution. I am also not sure how the jquery each can be leveraged here or how can this implementation be done using arrays. Can somebody point me in the right direction. I think we should use a function and pass that no. as a parameter, but I dont know how to use custom functions in jquery.
UPDATE:
This is what I have done
$(function() {
$('.p1').click(function() {
$('.div').hide();
$('.d1').show();
})
})
I have added the class div to all of my 50 divs and I am showing d1 on click of p1. Now how do I replace 1 for each instance till 50.
I would have a common class to all div and p so that the binding the handler and the hide can be simple. And for the div, I would associate a data-tag to each p to link each p tag to div
<p class="p1 pclass" data-showdiv="div1">
...
</p>
<p class="p2 pclass" data-showdiv="div2">
..
<div class="mydiv div1" ..>
..
</div>
<div class="mydiv div2" ..>
..
</div>
And the script would be,
$(function() {
$('.pclass').click(function(){
$('.mydiv').hide();
$('.' + $(this).data('showdiv')).show();
});
});
As Jason told,
Use this
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
If the div is next to each paragraph.
But, if there's an element between p and div, it wont work.
For you problem, you can do,
$('p').click(function() {
$('div').hide();
var divClass = $(this).attr("class").replace('p','div');
$('.' + divClass).show();
});
provided you have only p1, p2 .... in paragrah classes ;)
Update
See this fiddle
Notice , we have <br> tags between <p> and <div> as you wanted.
Assuming your HTML structure is
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
<p>Some text</p>
<div>More text to hide and show</div>
....
Use the following in your $(function(){}); method:
$('p').click(function() {
$('div').hide();
$(this).next('div').show();
});
var dvs = ['.div1','.div2','.div3','.div4','.div5','.div6',.........,'.div50'];
$('p').click(function() {
var index = parseInt(this.className.replace('p','')) - 1;
$(dvs[index]).show();
$(dvs.join(', ')).not(dvs[index]).hide();
});
The jQuery click event will automatically be registered on all elements that match the selector, so you shouldn't have to use the each() method. I would suggest having two CSS classes to distinguish between elements that have this toggling behaviour and elements that are primary (i.e. should be shown when their parent is clicked).
The markup:
<body>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p class="togglable">
<div class="primary">
This is the primary div that will be shown when our parent is clicked.
</div>
<div>Regular div child</div>
<p>Nested paragraph</p>
<ul>
<li>A list perhaps</li>
</ul>
</p>
<p>This is a normal paragraph</p>
</body>
The code:
$(function () {
$('.togglable').click(function () {
// hide all our children
$(this).children().hide();
// now only show our primary chlid
// NOTE: we pass 'this' as the second argument
// so that the selector will only apply to the
// children of the element that was clicked
// (i.e. we are providing a custom context for the selector).
$('.primary', this).show();
// You could even use the position of the child as well:
// $(this).children().first().show();
// This will show the first child element.
});
});
In this example all elements with the class togglable will show their primary child element when clicked and hide all other child elements.

jQuery replaceWith not loading div properly

I'm new to jQuery but am hoping to replace a <div> with another that contains a slideshow when I click on a link. The problem with my code however is that when I click the link, the <div> I want to load isn't showing. Instead I just see div.slidesContainer for example.
My HTML:
<div id="leftText">
<h2>Heading.</h2>
<p>Text. <a href="/" id ="startSlide" %>'Learn more.'</a></p>
</div>
<div id="slide">
<div class="slides_container">
<div>
<h1>Slide heading.</h1>
<p>Slide text.</p>
</div>
</div>
</div>
My jQuery:
$(function(){
$("a#startSlide").click(function(){
$('div#leftText').replaceWith('div#slide');
return false;
});
});
Here's a jsFiddle if it'll help: http://jsfiddle.net/HR43b/
You need to pass an HTML or jQuery object to replaceWith: http://api.jquery.com/replaceWith/
.replaceWith( newContent )
newContentThe content to insert. May be an HTML string, DOM element,
or jQuery object.
.replaceWith( function )
functionA function that returns content with which to replace the set
of matched elements.
String:
$('div.inner').replaceWith('<h2>New heading</h2>');
Object:
$('div.third').replaceWith($('.first'));
Callback:
$('div.container').replaceWith(function() {
return $(this).contents();
});
You have to pass a selector, not a string:
$(function() {
$("a#startSlide").click(function() {
$('div#leftText').replaceWith($('#slide'));
$('#slide').css('visibility', 'visible');
return false;
});
});
Demo: http://jsfiddle.net/HR43b/3/
Try this.
$('div#leftText').replaceWith('<div id="slide"></div>');
Or
$('div#leftText').replaceWith($('div#slide'));
Check this:
div#slide {
visibility:hidden;
}
your <div> is hidden.. before replacing with other content change its behavior to visible.
and then use replaceWith
your altered jsfiddle
$(function(){
$("a#startSlide").click(function(){
$('div#slide').css('visibility','visible');
$('div#leftText').replaceWith($('div#slide'));
return false;
});
});

multiple div using the same class open at once

I am using the javascript function for multiple hide show divs in custom tumblr theme.. my The problem is as the class name is same, if i click on a single div, by default all the div gets show or hide.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$(".toggleme").click(function () {
$(".toparea3").slideToggle("slow");
return false;
});
});
</script>
<a class="toggleme" href="#"><img src="http://www.abc.com/images/share.png"></a>
<div class="toparea3" style="display:none;">
<div class="share-bar clearfix" style=" margin-top:3px;margin-left: -2px;width: 380px;height: 50px;">
<div class="share-bar-buttons">
<div class="share-bar-facebook">
<iframe src="http://www.facebook.com/plugins/like.php?href={URLEncodedPermalink}&layout=button_count&show_faces=false&width=110&action=like&font=lucida+grande&colorscheme=light&height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:110px; height:21px;" allowTransparency="true"></iframe>
</div>
</div>
<div style="margin-left:80px;margin-top: 15px;" class="share-bar-twitter">
<a href="http://twitter.com/share" class="twitter-share-button"
data-url="{Permalink}"
{block:Twitter}data-via="{TwitterUsername}"{/block:Twitter}
data-related="stylehatch:Premium Tumblr Themes by #newezra"></a>
</div>
<div style="float: right;margin-top:-25px;" class="share-bar-shorturl">
<div class="linktumb">
http://www.tumblr.com/xdrs2sf
</div>
</div>
</div>
</div>
Assuming you have multiple "toggleme" buttons, if they're all in the format where you have a toggleme button and then a toparea3, you could do something like this:
$('.toggleme').click(function(){
$(this).next().slideToggle('slow');
return false;
});
The "next" function gets the next element in the DOM, which is the element you want to expand.
Edit: (nevermind the .children)
try using the .closest selector, or the .next selector someone else suggested. Just remember to provide the selector .toparea3 to make sure that only that class opens, not just any closest/next element.
$(document).ready(function() {
$(".toggleme").click(function () {
$(this).closest(".toparea3").slideToggle("slow");
return false;
});
});
I would recommend the following:
Place the 'a' and the corresponding 'div' in a parent 'div'. Something like this:
<div>
<a class='toggleMe' />
<div class='toparea3 />
</div>
Then you can update your inner selector to be:
$('.toggleMe').click(function(evt){
evt.preventDefault();
var parent = $(this).closest('div');
$(".toparea3", parent).slideToggle("slow");
}
My Recommendation is to give the div an id, and make the anchor element's href point to it:
<script>
$(document).ready(function() {
$(".toggleme").click(function () {
$(this.hash).slideToggle("slow");
return false;
});
});
</script>
<a class="toggleme" href="#toparea3_1"><img src="http://www.abc.com/images/share.png"></a>
<div id="toparea3_1" class="toparea3" style="display:none;"></div>
This since the hash is given in the form #toparea3_1 that is a valid jQuery selector that selects on ID, and can be used directly.

Categories