How do I move DOM elements with jQuery ?

jQuery

jquery-logo - appendToThe jQuery.appendTo method makes it easy to move a DOM element. You won’t need to be concerned with creating or destroying elements and event handlers are preserved.

Moving DOM elements using vanilla JavaScript can be a bit tedious. It’s certainly possible, and it is a good idea to understand the steps, but it does require more code. jQuery provides powerful abstraction for this task, however, and the amount of code needed is minimal.

Whenever possible, I favor using vanilla JavaScript to solve a problem, because leaning on jQuery too much can weaken your overall JavaScript skills. In this case, however, I recommend letting jQuery do all of the work for you. The main issue with vanilla JavaScript when it comes to moving DOM elements is the need to understand the intricacies of the low-level hierarchical DOM API. For example, you’ll need to get ahold of the parent element of the DOM node, after which you’ll want to move your target element. Frankly, I commend anyone who wants to take on this challenge, but in many cases, it just makes sense to leverage jQuery.

Try it yourself !

See the Pen Moving DOM elements with jQuery by Front End Video (@frontendvideo) on CodePen.

In the above example, click the “HTML” tab. There are two DIVs with the IDs: “left-list” and “right-list“. DIV#left-list has an unordered list with the days of the week, and DIV#right-list is empty. Now click the “JS” tab. You’ll see that there is a click-event handler for $('#left-list li'). This means that when any of the list items are clicked, the anonymous function you see will be executed.

Go ahead and click each of the days of the week and you’ll see that it is moved to the DIV#right-list element. After each element is moved, if you click it, nothing happens.

In the anonymous function, we use the JavaScript this keyword to reference the element that was clicked. Actually, we wrap the JavaScript this keyword with jQuery: $(this). We then chain the .appendTo method, and pass it a target element: .appendTo( $('#right-list') ). Here we are telling jQuery: “Move this element to the #right-list element, and make it the last child“. So, we are appending it to DIV#right-list. We then chain this: .unbind('click');. The reason we do that is: the jQuery appendTo method retains any event bindings for elements that are moved. Most of the time, this is probably what you want. But in this case, we do not want the event bindings to travel with the element because once a list item is moved inside of the #right-list element, we no longer want it to have a click-event handler. But that is simply for this example.

Summary

Simply put, moving DOM elements with vanilla JavaScript can be messy business, but the jQuery.appendTo method provides abstraction that simplifies this process. Instead of having to dig into the low-level DOM API, you can simply specify the source and target HTML elements. In other words, you let jQuery know which element you want to move, and which element you want to append it to. In cases such as these, it’s often best to let jQuery do all of the work for you. It will certainly minimize the amount of boilerplate coding you’ll have to do, and will help to keep your JavaScript easier to manage.

What are the Four Types of Position in CSS, and How Do They Differ?

CSS

JavaScript LogoIf you are a Front-End Web Developer you absolutely must be comfortable discussing CSS positioning. In this article, we’ll take a close look at each of the four types of position in CSS and how they differ

Static Positioning

“static” is probably the easiest of all four values to explain. It is the default position for any HTML element. Even when you do not specify a position value, the value of “static” is applied to that element’s position property. The easiest way to define the “static” positioning value is that when assigned, an HTML element behaves exactly as you would expect. I say this because you have probably written hundreds if not thousands of lines of CSS where you did NOT specify the position value. When you do not specify the position value, the value is “static”, and the behavior is what you would normally expect from an HTML element.

Fixed Positioning

“fixed” is the second easiest of all four values to explain. When fixed positioning is applied, an html element is positioned absolutely, relative to the browser window. It is completely removed from the document flow and has no physical effect on any other element in the DOM. The “top”,”bottom”, “left” and “right” properties can be used to “nudge” the element around, but that is it: nothing else will move that element away from its “fixed” position. Even when the document is scrolled, the target element retains its “fixed” position, relative to the browser window.

Example # 1 A

Example # 1 B

In Example # 1A, the element with the class “.fixed” is nudged 25px in two directions. What can be deceiving is that these values are “offset from”. So, if you specify a “right” value of “25px”, the element will be moved 25px “from” the right (i.e. not “to” the right). So, the effect can be the opposite of what you might expect. The JsFiddle.net link below provides an expanded demonstration of this.

Here is the JsFiddle.net URL for Example # 1A: http://jsfiddle.net/WRuDs/

In Example # 1B, the element with the class “.fixed” is again nudged 50px in two directions. The difference here is that a negative value has been provided for the “right” property. The net result is that the element appears to be nudged “in the direction of” the specified property (i.e. 50px “to” the right), so it appears cut-off because it is 50px out of view. The JsFiddle.net link below provides an expanded demonstration of this.

Here is the JsFiddle.net URL for Example # 1B: http://jsfiddle.net/sLGz7/

Relative Positioning

When the “relative” value has been provided for the “position” property, the specified element will be positioned relative to its normal flow in the document. This may seem a bit odd at first, but think of it this way: When you simply position the element relatively, and do nothing else, nothing happens visually. But if you then specify a “top”, “bottom”, “left” or “right” value, then the element is moved in whatever direction you specified, in the amount specified (i.e. pixels, inches, em, etc…).

An important note about relative positioning is that the element’s effect on the document flow does not change. For example, if you position an element relatively and assign the “top” to “-25px” and the “left” to “-25” it will appear 25px higher and to the left of where it would normally appear in the document. But as far as the DOM is concerned, that element’s position has not changed. The point here is that “nudging” an element in any direction has no effect on the DOM. The effect is purely visual. When you look at the JsFiddle.net example link below, you can see this exact behavior in the element with the class “upAndOver”. The element appears “nudged” up 25px and over 25px, but the space that it would have normally occupied in the document flow is very much in plain sight (i.e. its “up and over” appearance has not affected the document flow).

Example # 2

Here is the JsFiddle.net link for an expanded version of Example # 2: http://jsfiddle.net/etAKb/

Absolute Positioning

When an element is positioned absolutely, it is positioned absolutely relative to the nearest containing element that has positioning. The browser will traverse the DOM starting with the element’s containing parent and then its descendants, until it finds one that is positioned relative, absolute or fixed. When it finds one, then it positions the target element absolutely, relative to that containing element. If it does not find a containing element and reaches the HTML element, then the target element is positioned absolutely, relative to the HTML element.

Just as with relative and fixed positioning, “top”, “bottom”, “left” or “right” values can be provided so that the exact location of the element can be specified. Unlike relative positioning, an absolutely positioned element is completely removed from the document flow and has no physical effect on any other element in the DOM. However, a byproduct of absolute positioning is that the target element will appear to have its “z-index” higher than any element that it comes into visual contact with. By default, it will appear “on top of” any element that it overlaps with. Any siblings of the target element that share the same absolute positioning will appear “on top” of the previous sibling, in the order in which they appear in the markup.

For working examples of CSS Absolute Positioning, see my earlier post: CSS Absolute Positioning – The Basics | Kevin Chisholm – Blog

Summary

In this article we learned about CSS Positioning. We learned about static, fixed, relative and absolute. In each case, we learned how the target element interacts with the natural document flow

Helpful Links for CSS Positioning

https://developer.mozilla.org/en-US/docs/Web/CSS/position

http://alistapart.com/article/css-positioning-101

http://css-tricks.com/video-screencasts/110-quick-overview-of-css-position-values/

http://www.codecademy.com/courses/web-beginner-en-6merh

http://blog.teamtreehouse.com/css-positioning

Harnessing the Power and Simplicity of jQuery.append() and jQuery.prepend()

jQuery

JavaScript LogoI’m a big believer in making sure that you understand what is going on under the hood when you use jQuery. But there are times when it just makes sense to leverage jQuery; otherwise you would literally wind up just writing your own library.

One of the many such cases is when it comes to creating elements and then injecting them into the DOM. So let’s jump right into a few examples which will make it easier to highlight these features.

First, here is the markup we will be working with for all of the examples:

 

Native JavaScript

Example # 1:

Here is the JsFiddle link for Example # 1: http://jsfiddle.net/pvwP4/

When it comes to injecting new elements into the DOM, these methods virtually eliminate the verbose syntax of Native JavaScript

In Example # 1, I wanted to quickly review the absolute minimum native JavaScript needed to append text to an element in the page. Needless to say, if you want to accomplish anything useful, such as appending an unordered list, or complex markup that involves nested elements or images, etc., then you will wind up writing a bit of code. That’s just the state of native JavaScript today.

I tend to use jQuery as little as possible, mainly as an exercise in keeping my native JS skills sharp. But when it comes to creating and appending elements, jQuery.append() and jQuery.prepend() are hard to beat. It just saves so much time.

jQuery.append()

Example # 2: 

Here is the JsFiddle link for Example # 2: http://jsfiddle.net/tWSW8/

So, in Example # 2, our three lines of JavaScript have been reduced to one line of jQuery. Nice.

Example # 3:

Here is the JsFiddle link for Example # 3: http://jsfiddle.net/9pHQ2/

And here in Example # 3, we get into the fun stuff. First, one of the absolute joys of jQuery: the ability to create a DOM element by simply passing a set of opening and closing HTML tags to the $() method. Here I pass in an opening and closing DIV tag, and that’s it; we now have a reference to a new element that, while not yet in the DOM, is in memory and fully available to us for whatever we need. We then use a for loop to create LI elements using string concatenation.

Example # 4:

Here is the JsFiddle link for Example # 4: http://jsfiddle.net/mExAw/ In Example # 4, we start to put jQuery.append() to work. So inside of a for loop, we dynamically create list items, and append them to an unordered list. In order to keep things simple, we just use the value of the counter as the text. A more real-world example would be consuming JSON, and for each item in that JSON, creating the markup we need for the page.

Example # 5:

Here is the JsFiddle link for Example # 5: http://jsfiddle.net/JMy2J/

So now, in Example # 5, we turn things around by using the jQuery.appendTo() method. It could not possibly be simpler. Instead of UL.append(LI), we just say: LI.appendTo(UL). In other words, first we said: “…to that UL, append this LI”, and now we are saying: “…append this LI to that UL”.

jQuery.prepend()

Example # 6:

Here is the JsFiddle link for Example # 6: http://jsfiddle.net/D3B7G/

In Example # 6, we demonstrate the jQuery.prepend() method. There certainly is no mystery to this: it provides the opposite functionality of jQuery.append(). We create an unordered list, just as we did in the previous examples, but then we create another set of LI elements, and prepend them to the UL. I specifically counted down from 10, so that it would be obvious in the example that we have used jQuery’s prepend() method, and not append().

Example # 7:

Here is the JsFiddle link for Example # 7: http://jsfiddle.net/HqKv7/

Example # 7 is virtually the same as Example # 6, except we use jQuery.prependTo(), instead of jQuery.prepend().

Summary

Although this post is focused on jQuery.append() and jQuery.prepend(), we’ve also seen how easy it is to create elements with the $() function. While it is always good to make sure you understand what jQuery is doing and that you can write native JavaScript to accomplish your tasks, jQuery just makes perfect sense in many situations. As you can see, the main reason is that it abstracts away a lot of the time-intensive tedium of cross-browser compatibility.

Helpful Links for jQuery.append() and jQuery.prepend()

jQuery.append()

http://api.jquery.com/append/

http://www.w3schools.com/jquery/html_append.asp

jQuery.prepend()

http://api.jquery.com/prepend/

http://www.w3schools.com/jquery/html_prepend.asp