So here's my code:
<input type = checkbox id = "kinch" name = "link" > Bunz </input>
<div id = bootypipe></div>
Here's the JavaScript:
$("#kinch").click(function(){
if ($("#kinch").is(":checked")) {
//Add image to div bootypipe
$("#bootypipe").append("<image id = 'chink' src = 'http://4.bp.blogspot.com/_TUdhYRa2Xm0/RsuDa4NvSEI/AAAAAAAAAQs/jr_r6v_SUgs/s320/New-England-Style-Hot-Dog-Buns_8A827671.jpg'>HA!</image>");
} else {
$("#chink").remove();
}
});
Here's the jsfiddle: http://jsfiddle.net/shrimpboyho/wUu34/13/
The image removes and appends, but when I remove the image the text Ha! still stays and builds up over time. How can I remove this?
Cant you just do :
$("#bootypipe").empty();
instead of removing image.
Because you only remove the image tag not the text. You could do like this
wrap the image and text with one div and then remove the div tag like
$("#kinch").click(function(){
if ($("#kinch").is(":checked")) {
//Add image to div bootypipe
$("#bootypipe").append("<div id='chink_outer'><img id = 'chink' src = 'http://4.bp.blogspot.com/_TUdhYRa2Xm0/RsuDa4NvSEI/AAAAAAAAAQs/jr_r6v_SUgs/s320/New-England-Style-Hot-Dog-Buns_8A827671.jpg'/>HA!</div>");
} else {
$("#chink_outer").remove();
}
});
Demo
<image id = 'chink' src = 'http://4.bp.blogspot.com/_TUdhYRa2Xm0/RsuDa4NvSEI/AAAAAAAAAQs/jr_r6v_SUgs/s320/New-England-Style-Hot-Dog-Buns_8A827671.jpg'>HA!</image>
is invalid HTML markup; the element can't actually contain text. And the correct tag is <img>. I suspect it is actually being interpreted as
<img id='chink' src='...' > HA!
meaning the text isn't part of the element, and isn't removed with it.
Instead of doing $('#chink').remove(), do $('#bootypipe').empty() to remove everything you added.
The <img> element is self closing, like <br> or <hr> (your demo code is invalid, as mentioned in another answer).
But your code works, if you just include a wrapper (<p>,<span>,<div>) around the image. Then remove the wrapper (ie $('p').remove();). Do not add additional ids, classes (you've already created a function around #kinch. why add to the code?). Just target the wrapper. $('#chink').parent().remove(); works too, and it's unbiased to what element is the parent.
$("#kinch").click(function(){
if ($("#kinch").is(":checked")) {
$("#bootypipe").append("<p><image id = 'chink' src = '...'>HA!</p>");
} else {
$('p').remove();
// or $('#chink').parent().remove(); // pick your poison
}
});
Related
I have the following html (it's a card) where a class is added to change the look of it:
<div class="card-small-half" id="card-1">
<a href="components/">
<div class="action-bar">
<p>Add Page</p>
<i class="material-icons">add</i>
</div>
</a>
</div>
and a switch made with a label that checks and unchecks an input type checkbox:
<div class="switch-wrapper" id="switch-wrapper-1">
<input type="checkbox" id="input-1" class="display-none">
<label class="switch" for="input-1"></label>
<p id="switch-caption-1">Visible</p>
</div>
With the following Javascript I add a class called "card-disabled" to the card:
window.onload = function () {
function check() {
if (document.getElementById("input-1").checked) {
document.getElementById("switch-caption-1").textContent = "Disabled";
$('#card-1').addClass('card-disabled');
} else {
document.getElementById("switch-caption-1").textContent = "Visible";
$('#card-1').removeClass('card-disabled');
}
}
document.getElementById('input-1').onchange = check;
check();
}
I know in css you can call id's or classes like so:
#switch-wrapper-1 input { /* styles */ }
or
#switch-wrapper-1 p { /* styles */ }
How can I do this with javascript, so I don't have to use an id for every element and instead use a global id for every wrapper.
EDIT:
The wrapper and input id's are unique! I want to call the paragraph inside the unique wrapper element something like this:
document.getElementById("switch-wrapper-1 p").textContent = "Disabled";
The 'p' here means paragraph
Is this possible and if so: how?
Query Selector is your friend here. You can use CSS selectors to retrieve DOM elements. In your case this call would return the first paragraph child in the #switch-wrapper-1 element.
var node = document.querySelector('#switch-wrapper-1 p');
If you also use jQuery, then as suggested in comments, you can simply use the $ function.
var $node = $('#switch-wrapper-1 p');
To select an individual element inside of an element with a specific ID using Javascript you can do:
document.getElementById('hello').getElementsByTagName('input')[0];
So in your example it would be:
document.getElementById('switch-wrapper-1').getElementsByTagName('input')[0].onchange = check;
The [0] is used because getElementsByTagName returns an array of all the child elements inside the parent element with the specified tag. Note that you will have to keep the unique ID on the input field if you want the for attribute on the label to function correctly.
I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.
I have a code which allows me to add certain "absentees", along with their ID's through a hidden form, to the absentees list when I click on them. When I click on it again, the "absentee" is removed from the absentees list. However, when I click on it again, the list seems to extend further because of a br
in my code plus the hidden form value doesn't seem to be removed. I need the hidden value removed so that the removed absentee from the list will not be recorded in the database. I need the br
so that the absentee listing will be presentable.
Here's my code: http://jsfiddle.net/gk5pV/8/
I wholeheartedly agree with #charlietfl, just use a block level element. Also, use a single hidden input to track your absentees. Example fiddle, code below:
$(function() {
$("td").click(function() {
var $this = $(this);
var user = $this.attr('id');
var p = $('<p />').attr('user', user).text($this.text());
var absentees = [];
if ($('#absentees').val().length > 0) {
absentees = $('#absentees').val().split(',')
}
if ($(this).hasClass('on')) {
//console.log("Already marked absent");
//remove from collection
$("#collect").children('p[user="' + user + '"]').remove();
absentees.splice(absentees.indexOf(user), 1);
}
else {
//console.log(user);
//add to collection
$("#collect").append(p);
absentees.push(user);
}
$this.toggleClass('on');
$('#absentees').val(absentees.join(','));
});
$("#clicky").click(function() {
$('td').removeClass('on');
$("#collect").empty();
$('#absentees').val('');
});
});
Solution is fairly simple. Wrap the text you want to append and hidden input in a block level element ( div, p, li etc) and you won't need a <br tag. WHen you remove the absentee from list you remove the block element and the input will be part of it so it will no longer exist. If you give the new block level element a class name you can simply attach your event handler to the class
I have a div contentEditable with paragraphs and appended after each p is a span telling me the length of the paragraph the user can edit the line & thus update the number shown in the span, (done with something on these lines .each(fu..(){ p append '<span>'+ this.length ..)
Let's say something like this:
<div contenteditable="true">
<p>abc<span contenteditable="false" style="position:absolute;right:-2em;backg...">3</span></p>
<p>abce<span ...>4</span></p>
<p>abcfoo<span ...>6</span></p>
<p>abcbar<span ...>6</span></p>
</div>
Have made all the spans uneditable in order to protect the spans and the text, on hitting return a new <p> is created on the next line - all sparky! However I have no way of deleting a new paragraph as the back button on the first letter of a p acts as the browser back button! because its hitting the non editable span.
So I would like to add a button (perhaps on the span) which when clicked will 1. remove the span (not too difficult), 2. merge the 2 paragraphs together.
I hope that's the effect you're looking for: http://jsfiddle.net/AwKkB/
JS
$('span').click(function () {
var parent = $(this).parent(), container = parent.parent();
$(this).remove();
if (container.children().length > 1) {
if (parent[0] === container.children()[0]) {
$(container.children()[1]).prepend(parent.text());
} else {
parent.prev().append(parent.text());
}
}
parent.remove();
});
HTML
<div contenteditable="true" style="width: 180px">
<p>abc<span contenteditable="false" style="position:absolute;right:0em;background: red;">3</span></p>
<p>defg<span contenteditable="false" style="position:absolute;right:0em;background: red;">4</span></p>
<p>hijklm<span contenteditable="false" style="position:absolute;right:0em;background: red;">6</span></p>
<p>nopqrs<span contenteditable="false" style="position:absolute;right:0em;background: red;">6</span></p>
</div>
Best regards!
Something like this should do it:
$(document).on('click', 'span', function() {
$(this)
.prev().append($(this).next().text()).end()
.next().remove().end()
.remove()
;
});
See Fiddle.
I'm not sure whether the paragraphs contain only plain text, but a generalised way would be using .append, so that all elements are left intact: http://jsfiddle.net/tb7xk/.
$("<input>")
.attr({ type: "button", value: "Remove" })
.click(function() {
var $span = $(this).parent();
var c = $span.next().contents().get(); // contents
$.fn.append.apply($span.prev(), c); // pass all contents to .append
$span.next().andSelf().remove(); // remove next paragraph that's left over
})
.appendTo("span");
I have 4 divs in a container. I want to display the html of the container which contains the divs in the textarea. I'm able to do this. The issue is, i don't want to get all the html of the container. I don't want to get #iv #three. I want to copy all the html of the container except div #three. I could use $('#three').remove() but i don't want to remove the div, I just don't want to copy it's html value to textarea. Check jsfiddle http://jsfiddle.net/rzfPP/
<div id="container">
<div id="one">test 1 </div>
<div id="two">test 2 </div>
<div id="three">test 3 </div>
<div id="four">test 4 </div>
</div>
<textarea id="save"></textarea>
var x = $('#container').html();
$('#save').val(x);
Try this
$("#container").clone().find("#three").remove().end().html();
http://jsfiddle.net/rzfPP/21/
/*
var x = $('#container').html();
$('#save').val(x);
*/
var lol = $('#container').clone()
$(lol).find('#three').remove();
$('#save').val(lol.html());
$('#container').clone().find('#three').remove().end().html();
Technically this is illegal since you are duplicating IDs, but it works fine.
http://jsfiddle.net/rzfPP/33/
Edit: Someone beat me to it :( Oh well.
var text = "";
$('#container div').each( function() {
if ( this.id != "three" ) {
text += $(this).html();
}
});
$('#save').val( text );
http://jsfiddle.net/rzfPP/31/
Basically you check the divs inside #container one by one, and check their id. If it's one you want, add their html to a string. Then at the end give that string as your textarea value.