jQuery toggle() text in separate element - javascript

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.

You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.

<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>

try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!

I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Related

How to check if a specific div element is created or not?

I want to check if following code is dynamically created or not :
<div id="js_contact_error_message" style="display: block;">
<div class="error_message"> <!-- For this div only I want to apply the above written inline css-->
Please enter full name
</div>
How should I check this in jQuery? If it's present execute the if condition.
Thanks.
The condition that <div class="error_message">...</div> is present within <div id="js_contact_error_message" style="display: block;">...</div> must get checked.
I tried below code but it didn't work for me:
if ($("#js_contact_error_message").find("div.error_message").length != 0) {
alert("Bestow");
}
You can do this:
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
Note:
You need to place this line of code where you have done your js validations.
or you may try with this:
$(document).on('DOMSubTreeModified propertychange',function(){
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
});
Try,
For using if-else condition.
if($("#js_contact_error_message").find(".error_message").length > 0)
{
alert("div present");
}
else
{
alert("div not present");
}
But as you stated in your question, you want to apply specific inline css. Make a class for the style what you have and you can use the ollowin code.
$("#js_contact_error_message").find(".error_message").addClass("your_style_class");
This code will apply your css class only for those divs which match the condition.
EDIT:
If you want to add your style to the div, you can try defining it in your page, which will apply as soon as the div is added dynamically.
<style>
#js_contact_error_message .error_message
{
/*your inline style*/
}
</style>
if($("#js_contact_error_message .error_message").length > 0)
{
alert("div is present");
}
else
{
alert("div is not present");
}
Demo
You can check it in many ways.. few of them are :
Use $("#js_contact_error_message").has('div') function of jquery to get the specific element Has in JQuery
If the error message div is the only div to be inside the main div then you can check it as :
Check the element $("#js_contact_error_message").html() is blank or use $("#js_contact_error_message").children() (Children in JQuery) to check if it has any childrens.
Hope this helps :)
make sure your html composition is correct , opening and closing. Then try this code.
if($("#js_contact_error_message").length > 0)
{
$("#js_contact_error_message").find(".error_message").addClass("style_class");
}

jQuery.each() class example Appending Div Text to Li

$EACH DEMO
anyhow iam getting the text of "div class": and printing in console.,
and iam trying to append the same text in "li > button", which is not happening, not sure where iam going wrong,
html :
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
JS:
//step - 1
$.each($('.productDescription'), function() {
var classTxt = $(this).text();
console.log(classTxt);
});
//outputs: Red Orange Green
//step - 2 now im trying to append the text to li
var liBtn = $(this).find('li').next('button');
console.log("Text of Button - "+ classTxt);
console.log(liBtn)
for (var i = liBtn.length; i >= 0; i++) {
liBtn[i]
};
Appreciate Your Help, Thanks
There are several errors in your code. classTxt is undefined outside of the each handler's context and the second this refers to window object and not to the .productDescription elements.
I'd suggest using the .append() method's callback function:
// cache the collection for better performance
var $p = $('.productDescription');
$('li button').append(function (index) {
return $p.eq(index).text();
});
http://jsfiddle.net/46yo7etz/
You could also use the .text() method:
$('li button').text(function(index, currentTextContent) {
// using indices for selecting
// the corresponding `.productDescription` element
return currentTextContent + $p.eq(index).text();
});
Please note that your fiddle's markup is invalid. li element should be child of an ul/ol element.
$('li > button').text(function() {
return $('.productDescription').eq( $('li > button').index( this ) ).text();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
$("button").each(function(i){
$(this).text( $(".productDescription").eq(i).text() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDescription">Red</div>
<div class="productDescription">Orange</div>
<div class="productDescription">Green</div>
<ul>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
</ul>
http://jsfiddle.net/simply_simpy/uqmpvb7e/

Show/hide div on click if div class names match

I have two sets of divs — one that is the 'main' div and one that is the 'extra' div. Both of these have classes that are brought in via the CMS.
What's the best way of showing/hiding (preferably slideToggle) each div, on click, that corresponds to the div clicked?
<div class="each-business-content-main" data-id="group-1"></div>
<div class="each-business-content-main" data-id="group-2"></div>
<div class="each-business-content-extra group-1"></div>
<div class="each-business-content-extra group-2"></div>
These 'group-1' or 'group-2' classes aren't known in advance so can't be hard-coded in. Essentially I'm wondering how, if you click on one div it shows another div (as long as they share the same class name).
I've tried this so far:
$('.each-business-content-main').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
jQuery('.each-business-content-extra').slideUp();
jQuery('.each-business-content-extra .' + id).slideDown();
});
But I'm guessing hrefs and id might come in useful? Or some other data-id...
If you assign a data attribute to your divs it makes this pretty easy:
<div class="each-business-content-main group-1" data-group="1">main 1</div>
<div class="each-business-content-main group-2" data-group="2">main 2</div>
<div class="each-business-content-extra group-1" data-group="1">extra 1</div>
<div class="each-business-content-extra group-2" data-group="2">extra 2</div>
$('.each-business-content-main').click(function () {
$('.each-business-content-extra.group-' + $(this).data('group')).slideToggle();
});
jsFiddle example
Have you tried replacing this:
jQuery('.each-business-content .' + id).slideDown();
...with this:
jQuery('.each-business-content #' + id).slideDown();
jQuery selects classnames as .classname and IDs as #id.
Try
$('.each-business-content').click(function () {
var that = $(this);
$('.each-business-content').each(function () {
if ($(this) === that) {
$(this).slideUp();
} else {
$(this).slideDown();
}
});
});
Can you try this code at jsFiddle? Don't need group 1 and group 2, I use index instead of the name of the id. Is that all right for you?
$('.each-business-content-main').on('click', function (e) {
$('.each-business-content-extra').(':eq(' + $(this).index() + ')').slideDown();
$('.each-business-content-extra').not(':eq(' + $(this).index() + ')').slideUp();
});

Collapse HTML if no content found

I want to be able to remove HTML elements if they contain no content.
Let's say we have some markup and are targeting all 'collapse' classes:
<div class='collapse'>[CONTENT?]</div>
If there is some content then don't do anything.
But if there is no content - no string characters or whitespace - then remove the div element completely.
This is easy to implement in the simple cases but with nested content it's slightly more more tricky.
Here is a demo, if you try removing the [CONTENTX?] strings and then seeing what the HTML structure is you'll notice that it doesn't work completely.
If a div only has other divs with no content then that should be treated as no characters or whitespace.
If we remove all [CONTENTX?] strings then we should see no HTML structure.
What ways are there to handle this?
jsFiddle: http://jsfiddle.net/97udq/
HTML:
<div id='container'>
<div class='collapse'>
[CONTENT1?]
</div>
<div class='collapse'>
[CONTENT2?]
<div class='collapse'>
[CONTENT3?]
<div class='collapse'>[CONTENT4?]</div>
<div class='collapse'>[CONTENT5?]</div>
</div>
</div>
</div>
Javascript:
$(function(){
// function
collapse();
// Show HTML structure
alert($('#container').html());
});
function collapse(){
// Loop thru all collapse elements
$('.collapse').each(function(){
// Check for pure whitespace
if($(this).html().replace(/\s+/g, '').length==0){
// Nothing to see, so remove.
$(this).remove();
}
});
}
CSS:
.collapse{
height:20px;
border:1px solid red;
}
I think this does the job;
It just uses text() instead of html();
Here's the documentation.
This one adds the trim(), but I thik that's not what you want.
function collapse(){
$('.collapse').each(function(){
if($(this).text().length==0){
$(this).remove();
}
});
}
Here's another way of accomplishing what you want. It recurses down the DOM pruning nodes from the bottom up. Hope this helps.
function prune(root) {
$.each($(root).children(), function(){
prune($(this));
});
if($(root).html().replace(/\s+/g, '').length==0 && $(root).hasClass("collapse")){
$(root).detach();
}
}
Code integrated into your JSFiddle
You need to recreate the .each() loop, but reversed. Just like that :
function collapse(){
var el = $('.collapse');
for(var i = el.length - 1; i >= 0; i--){
if(el[i].innerHTML.replace(/\s+/g, '').length==0){
$(el[i]).remove();
}
}
}
It will remove the childrens first, then check for parent.
Here a fiddle : http://jsfiddle.net/97udq/5/
EDIT :
I missunderstood your question, here's the right solution :
function collapse(){
$('.collapse').each(function(){
var $this = $(this)
var clone = $this.clone();
clone.children().remove();
if(clone.html().replace(/\s+/g, '').length==0){
$this.children().appendTo($this.parent());
$this.remove()
}
})
}
Basicly, you clone the current div, remove its children and then check if there is some text. If there's none, you append his children to his parent
Fiddle : http://jsfiddle.net/97udq/9/

JQuery - Toggle an image inside of a div on click?

So I have a toggled div with an image inside of it that toggles the scrolling of the next div:
<div class="section">
<img src="on.png"> Stuff </div>
<div class="under" style="height:302px;"> Hi </div>
Here's the JQuery for it:
$(".section").click(function(){
$(this).next('div').slideToggle(1200);
});
How would I make it so on the click function for my div, it toggles the image to "off.png"? And if the src is "off.png", it toggles to "on.png"? Thanks. (Sorry I'm still a noob at JQuery)
$(function(){
$(".section").click(function(){
$("img").attr('src',
($("img").attr('src') == 'http://www3.picturepush.com/photo/a/2772891/64c/png/power-off.png?v0'
? 'http://kiwianon.com/forums/Themes/Simple_Green/images/on.png'
: 'http://www3.picturepush.com/photo/a/2772891/64c/png/power-off.png?v0'
)
)
});
});
demo
$(".section").click(function(){
var img = $(this).find("img").eq(0); //add an Id to your img tag so you can refine this selector.
if(img.attr("src") == "on.png")
{
img.attr("src","off.png");
}
else{
img.attr("src","on.png");
}
$(this).next('div').slideToggle(1200);
});
Ken, this is very simple! Just use the code below:
$('.section').click(function(){
var currentimg=$(this).find('img').attr('src');
if(currentimg=="off.png"){
$(this).find('img').attr('src','on.png');
}
else{
$(this).find('img').attr('src','off.png');
}
});
Use $(selector).attr("src", "theImageFilePath") to change the image.
The state could be represented in several ways, including global/module variable, $(selector).data(...), or simply by checking the current value of the "src" attribute.

Categories

Resources