Contents of a Div formatting differently when built through jQuery - javascript

I have the following DOM structure:
<div id="module-main">
<div id="module-crumbs">
<h4>Hello</h4>
</div>
</div>
When I place that in a document and view it, it works fine. But if I build it from jQuery like so:
$('#module-main').append($('<div id=\"module-crumbs\" />'));
$('#module-crumbs').append($('<h4/>').html('Hello'));
Instead of the H4 margins expanding within "module-crumbs" it'll expand just beyond "module-main" ... what is most confounding is that the DOM structure is exactly the same after jQuery runs. How does the browser calculate the margins and why does it matter if I do it through Javascript vs hand coding it if the results are the same? Any ideas?
Thanks!
Edit: While I marked the best answer as it re-wrote what I was doing in a much more readable manner, the real root cause of the problem ended up being collapsing margins that did not trigger with jQuery because the jQuery was calling module-crumb instead of module-crumbs and there was nothing to prevent the border from collapsing. Putting a 1px padding brought it together (a border would have worked as well).

The DOM resulting from the markup and that generated by jQuery is not the same - the html() method is not behaving as you expect it to.
The H4 element in the initial markup contains only a single text node.
To build the same DOM with jQuery, use:
$('#module-main').append($('<div id=\"module-crumbs\" />'));
$('#module-crumbs').append($('<h4/>').append('Hello'));
For a more markup-like representation (which can often be easier to read), try:
$('#module-main').append(
$('<div id="module-crumbs" />').append(
$('<h4/>').append('Hello')
)
);

Related

How do I style certain characters/words differently in CSS/js? without jQuery?

I need to select all of the commas in an HTML document to change their color. As far as I can tell this is not possible with CSS alone. My best guess is to use js to find and replace , with <span class='comma'>,</span> but I cannot figure out how to do this.
Well, if you do this for every element, it will be slow. Not like it can't be done, but it would be nice to at least have a parent container where you can search.
<div class="my-container">
<p>Some more, elements here.</p>
<span>Some</span> have, commas.
</div>
container = document.querySelector('.my-container')
html = container.innerHTML
newHTML = html.replace(/,/g, '<span class="comma">,</span>')
container.innerHTML = newHTML
.comma {
color: red;
}
You can see it running here.
If you really want to apply it to the whole document just replace the contents of document.body rather than container.
It would probably depend on how long the page is - gosuwiki's answer with JavaScript is most likely the easiest way for a relatively small file, but this would be run every time the page is loaded, which isn't usually optimal for larger pages or ones that are loaded often. Depending on your project's needs, it might be best to just run a find and replace operation in your IDE (or via a short script) to swap out the commas for <span>s. This question might also be of some interest to you - the answers seem to agree that such a selection cannot be done with pure CSS.

Updating a simple jQuery / CSS code

I was hoping someone could help me out with this simple question: I’ve just started to learn jQuery and found a code to show hidden text after selecting an item.
I’d like to update it so that:
a.) The selected item is bold
b.) I can add placeholder text instead of starting off with a blank hidden text field
I foolishly assumed I could solve a.) by using the :active property in css, but that only works as long as the link is clicked on. (As soon as you release the mouse button it’s gone.) Just like b.), this is probably only possible by using jQuery as well? If so, would be really great if you could show me how to solve it. :)
The codes: http://jsfiddle.net/KUtY5/1/
JS
$(document).ready(function(){
$("#nav a").click(function(){
var id = $(this).attr('id');
id = id.split('_');
$("#menu_container div").hide();
$("#menu_container #menu_"+id[1]).show();
});
});
CSS
#menu_container {
width: 650px;
height: auto;
padding-left: 30px;
}
#menu_container div {
display:none;
}
HTML
<div id='nav'>
<a id="show_apps">Appetizers</a> | <a id="show_soups">Soups and Salads</a> | <a id="show_entrees">Entrees</a>
</div>
<div id="menu_container">
<div id="menu_apps">
Content of the App Section Here
</div>
<div id="menu_soups">
Content of the Soups Section Here
</div>
<div id="menu_entrees">
Content of the Entrees Section Here
</div>
</div>
Updated fiddle
You can realize a) using a custom class bold for example and the following code :
CSS
.bold{ font-weight: bold;}
JS
$(this).addClass('bold').siblings('a').removeClass('bold');
For b) I can't find any textfield in your code.
Hope this helps.
I have added some extra lines to your code and you can check it from here http://jsfiddle.net/KUtY5/483/.
You bold like this
$("#nav a").css("font-weight", 400); // First you make them thin
$(this).css("font-weight", 800); // Than you make them bold
You put placeholder like this
<div id="placeholder">
Placeholder
</div>
$("#placeholder").hide();
On the other hand I recommend you not to hide menu container. Rather hide the elements inside the menu_container. So you can put a plcaeholder in menu container and you can hide it.
To figure this out 2 questions must be asked / solved
how do you normally make text bold on a page... css right?
where do you want those styles to be defined? There are 2 places:
a. You can define it inside the javascript.
b. You can define it inside the projects css through normal methods (inline, external, embedded).
What's the difference? If you define it inside the javascript the code is self-contained. What i mean by that is you can copy/paste the JS code from one project to the next and you don't need to worry about copying related styles from the stylesheets or other sources because it's all in the JQuery that you've written.
In contrast if you define it outside the javascript in the regular places the code may not be self-contained however some find it easier to manage in the scope of that particular project because all your css is contained in one place (external stylesheet typically).
If you want to take option a, see the .css() method
If you want to take option b, see the style manipulation (toggle class in particular)
Note the examples in the above references should get you 90% of the way to understanding it.
Some final words. Learn Jquery, but i advise you to stay away from it as much as possible because it implements DOM thrashing instead of DOM caching (sizzle engine).
This video series will briefly go into why Jquery sucks for performance in the first video and the rest of the series is about how to create modular vanilla JS.
JQuery goes back and searches the DOM every time you need to make a change that is what
$.(*element*) is doing instead of just caching it.
The more nodes you have in the DOM the more processing power is used searching (because it has to go through the entire tree).
Then on top of that the more elements you have to make changes to (say if you use a css class selector) you have to add even more processing on top of that.
All this is fine if you're on a desktop, but what about a mobile platform? Where would you get all this processing power from?... It doesn't exist.

jQuery append text formatting

This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:
$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');
Is it possible to convert this to a readable format, for example using multi-lines. I tried
$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')
This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.
If you have to add the HTML inline style I would suggest the following format.
var html =
'<div class="somediv">\
<div class="otherdiv">\
.
..
...
</div>\
</div>';
$('#somediv').append(html);
You can do it this way -
$('#someDiv').append($('<div>').append($('<span>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
)
You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)
$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")
My solution would be to create all these elements
div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);
container.append(..)
This means a lot of code but you can outsource it, can easily change attributes and its good readable...

setting content between div tags using javascript

I'm trying to set some content in between some div tags on a JSP page using javascript.
currently the div tag on the JSP page looks like this:
<div id="successAndErrorMessages"></div>
I want to fill the content in those div tags using some javascript method so that it will look like so:
<div id="successAndErrorMessages"><div class="portlet-msg-error">This is an error message</div></div>
I know you can go like this:
document.getElementById("successAndErrorMessages").value="someContent";
But that just changes the value of the 'value' attribute. It doesn't fill in content between those div tags. Anyone out there that can point me in the right direction?
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
See Creating and modifying HTML at what used to be called the Web Standards Curriculum.
Use the createElement, createTextNode and appendChild methods.
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

Weird margin when using .prependTo()

I've got some trouble in understanding the following behavior. I'm having a container <div> which contains a few inline-block <div> nodes. Example view:
Now my requirement is, to prepend new foobar inline-block <div> elements. No Problem, using jQuery -> .prependTo() to the rescue(applied on the parent container). Now comes the issue, the first time using .prependTo() "something, somewhere" creates an untrackable margin on the right side from the newly inserted element (it lookes like this to me). Example:
As you can see, only the very first element has this margin (again, I cannot track the space using Firebug/DevTools, it seems like its not there). All further insertions are just fine. Using .insertBefore() on the very first element also works fine and looks great. Unfortunatly I cannot use .insertBefore() in my particular usecase, that is why I'm asking for some heads-up here.
What do I miss ? Where comes this strange margin/spacing from ?
How to avoid it ?
Here is the jsfiddle playground where the above images come from:
http://jsfiddle.net/r7d6s/
I only tested on Firefox 4/5/6 so far.
It's the whitespace inside your parent div (i.e. line break). It gets sanitized to an ordinary space by HTML renderer. Remove it:
<div id="area"></div>

Categories