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

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.

Related

Append element AFTER load

I've got this code
$(".test_init").click( function(){
var win = $(this).next(".test_wrap").find(".test_drop");
if ($(win).html().length)
$(win).empty().hide("fast");
else {
$(win).load("URL");
}
});
Which returns me some html form without close button
I wish to add close button using such method without adding it in every-single function
$('*[class*="_drop"]').change(function() {
$(this).append($('<a />', {
class: 'close-drop',
click: function(e) {
e.preventDefault();
alert("test");
}})
);
});
But nothing happens - i can't understand why close button doesn't appends
<div class="test_wrap relative">
<div class="test_drop absolute"></div>
</div>
Example: http://jsfiddle.net/fppfyey7/10/
Your problem is with your CSS, not with your JS. The button is appended but you are hidding it with your style.
For example in this fiddle I append a button with your JS code and your CSS:
Fiddle 1
Now, in this one, I just remove your absolute and relative classes:
Fiddle 2
My solution (isn't good enough, still works)
$('*[class*="_drop"]').ajaxStop(function() {
$(this).prepend('<a onclick="$(this).parent().empty().hide(\'fast\');" class="close-drop"></a>');
});
If here will be better solution, will mark it as answear!

Append a div outside of the input parent

Im fairly new to javascript and I just can't figure this out despite my attempt in researching. How do I track the change of a input within a div and trigger an append to an outside div? My code goes as follow:
Append h3 with "Pending" once ".image-value" input has a change in value
<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
<div class="select-form">
<img src="images/vote.jpg" data-value="image_value">
<img src="images/vote.jpg" data-value="image_value2">
<img src="images/vote.jpg" data-value="image_value3">
<img src="images/vote.jpg" data-value="image_value4">
<img src="images/vote.jpg" data-value="image_value5">
<!-- Track the change of this input -->
<input type="hidden" class="image-value" name="selected_image" value="">
</div>
</div>
I tried this:
function changeStatus(statusValue) {
$("input",".select-form").val(statusValue).trigger("change");
}
$("input",".select-form").change(function(){
if (!$(this).val()){
$("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
}
});
But that didn't seem to work. Any ideas?
place an empty div where you want your new div and give it an id i.e(<div id='myDiv'><div>) and then append what you want like this.
$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );
You can also check Append Explained
for more explanations.
Thanks.
I've done a couple things here... First, I'm not sure why you had it all in a named function. When you're using event listeners that often isn't necessary.
Then, I don't know what the val check was for, so I reversed it.
Finally, I'm using one(), which only runs once. This case seemed to call for that.
$('.select-form').one('change', 'input', function () {
if ( $(this).val() ) { alert('asdgf');
$("<div class='pending'>Pending</div>")
.appendTo($(this).parent().prev('h3'));
}
});
Fiddle
try this:
$("input",".select-form").on("change", function(){
var $this = $(this);
if (!$this.val()){
var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');
$this.parent().parent().before(elem);
}
});
you can also place a check, that if the pending div is already added, not to add it again.
Of course this solution assumes that there are no other nested divs between the target div(before which you want to append) and the input control

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/

Show div once clicked and hide when clicking outside

I'm trying to show the #subscribe-pop div once a link is clicked and hide it when clicking anywhere outside it. I can get it to show and hide if I change the:
$('document').click(function() {
TO
$('#SomeOtherRandomDiv').click(function() {
HTML:
<div id="footleft">
Click here to show div
<div id="subscribe-pop"><p>my content</p></div>
</div>
Script:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById("subscribe-pop");
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
}
$('document').click(function() {
$('#subscribe-pop').hide(); //Hide the menus if visible
});
$('#subscribe-pop').click(function(e){
e.stopPropagation();
});
</script>
You have to stop the event propagation in your container ('footleft' in this case), so the parent element don't notice the event was triggered.
Something like this:
HTML
<div id="footleft">
<a href="#" id='link'>Click here to show div</a>
<div id="subscribe-pop"><p>my content</p></div>
</div>
JS
$('html').click(function() {
$('#subscribe-pop').hide();
})
$('#footleft').click(function(e){
e.stopPropagation();
});
$('#link').click(function(e) {
$('#subscribe-pop').toggle();
});
See it working here.
I reckon that the asker is trying to accomplish a jquery modal type of display of a div.
Should you like to check this link out, the page upon load displays a modal div that drives your eye into the center of the screen because it dims the background.
Moreover, I compiled a short jsFiddle for you to check on. if you are allowed to use jquery with your requirements, you can also check out their site.
Here is the code for showing or hiding your pop-up div
var toggleVisibility = function (){
if($('#subscribe-pop').is(":not(:visible)") ){
$('#subscribe-pop').show();
}else{
$('#subscribe-pop').hide();
}
}
Changing $(document).click() to $('html').click() should solve the main problem.
Secondly, you do not need the toggle_visibility() function at all, you can simply do:
$('#subscribe-pop').toggle();
Ref: changed body to html as per this answer: How do I detect a click outside an element?

jQuery toggle() text in separate element

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

Categories

Resources