I have the following html:
<p>This is some random text in a paragraph with a <span class="blue">blue</span> word.</p>
<p>This is some random text in a paragraph with a <span class="blue">blue</span> <i>word</i>.</p>
<p>This is some random text in a paragraph with a <span class="blue">blue</span> <span class="blue">word</span>.</p>
My CSS is as follows:
.blue{
color:blue;
}
.popup{
background-color:lightblue;
}
And finally my JS:
var popup = false;
$(".blue").click(function(){
if (!popup){
$(this).after("<div class='popup'>This is some popup text</div>");
popup = true;
}
else{
$(".popup").remove();
popup = false;
}
});
Now my problem, when I call the remove function on my popup class it removes whitespace between tags As explained in some answers below, the after function could also be causing this. . eg:
<span class="blue">blue</span> <i>word</i>
becomes
<span class="blue">blue</span><i>word</i>
It does not do this when the text following a blue class is not in tags eg:
<span class="blue">blue</span> word
Why does this happen and how can I prevent it?
For further reference here is a fiddle: http://jsfiddle.net/6fqDq/
Edit: It seems this problem is localized to Chrome as it does not occur in FF or IE.
Answer: Use the jQuery $. trim() function You can use the jQuery $. trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
jQuery remove() Method The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.
hide() sets the matched elements' CSS display property to none . remove() removes the matched elements from the DOM completely. detach() is like remove() , but keeps the stored data and events associated with the matched elements.
The reason this is happening is because you added a block element(div), the block element breaks into a new line, then when it's removed, it takes away the whitespace with it that's after it, because for HTML a whitespace and a newline is pretty much the same.
You have several solutions, some were mentioned here :
 
<i>
tag instead of between tags, so <i> word</i>
would work fine. <span>
tag instead of a div tag on the after
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With