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.

How do I detect a text-input change event with Angular?

Angular

Angular logo -routing
If you want to act upon the change event of a text input or text area, assign a method to the change attribute.

Okay, let’s start with the basics. Let’s say an HTML text input is simply sitting there, waiting for the user to click the form’s submit button, after which your JavaScript code would take that text input’s value and send it as part of the HTTP POST request. But what if you don’t want to wait; what if you want to know if the user has made a change to the text input. Let’s use form-validation as a typical case; let’s say you want to know if the user has entered a valid value. For example, you might want to enter an email address, a telephone number, or a social security number. Well, by assigning an event handler to the element’s (change) attribute, you’ll be able to act upon any change in the text input.

Let’s take a look at a couple of examples:

Example # 1

In Example #1 we have our component. We will consume the changeCount property in our template.

Example # 2

In Example # 2, we have our template. In the H3 tag, we use the {{changeCount}} placeholder to show the value of the changeCount property. The text input has a change attribute. For the value, we assign an expression: “changeCount = changeCount + 1”. This means that each time the change event fires on that text input, the changeCount property is incremented by one. Thus, each time the user makes a change to that text input, the UI message “You have made {{changeCount}} changes so far.” is updated and the {{changeCount}} placeholder  shows the current value of the changeCount property.

So, for the sake of simplicity, we have incremented the value of the changeCount property inline. That is, instead of assigning a method to the text input’s (change) attribute, we assign an expression. Now even though this approach is not a recommended pattern, it does have the advantage of being valid and easy to read. So the best approach is the normal one, which is to assign a method to the (change) attribute. And that method would be a property of our HomeComponent.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-change-attribute

How do I disable an HTML element with Angular ?

Angular

Angular logo - disable an html element

Set the disabled attribute to the result of an expression and Angular will disable / enable the element for you as needed.

Disable an HTML Element – Example # 1

In example # 1, we have our component. There are two properties we are interested in: count and buttonDisabled. We will leverage these in our template.

Disable an HTML Element – Example # 2

In example # 2, we have our template. There are three buttons. The first two buttons toggle each other. That is to say, when the first button is clicked it is destroyed, and the second button is created. Conversely, when the second button is clicked, it is destroyed and the first button is created. All of this happens because each button has an ngIf attribute. That attribute is watching for the value of the buttonDisabled property. Also, each button has a click attribute. In each case, clicking the button updates the value of the buttonDisabled property.

Important note: these two buttons are for demonstration purposes only. The focus of this article is the Angular [disabled] attribute.

Next, take a look at the third button. It has a disabled attribute. That attribute is set to toggle based on the buttonDisabled property. So when the buttonDisabled property is true, that third button is disabled. And when the buttonDisabled property is false, the third button is not disabled.

Video Example Code

If you want to download the example code, visit this Github page, and then follow the instructions: bit.ly/kcv-angular-disabled-attribute

Getting Started with HTML5 Drag and Drop Part IV: Multiple Draggables and Multiple Droppables

HTML5

HTML5 LogoOnce you know how to successfully drag one HTML element and drop it on another one, there is a new UX challenge: multiple elements that can be dragged and then dropped on any one of multiple droppables.

In Parts I, II and III of this series, we covered the critical concepts needed to implement HTML drag and drop. There, we talked about the dragstart event, the dataTransfer object, originalEvent object, drop event, dragenter event, dragleave event, and setDragImage method. These concepts got us to the point where we could drag one HTML element, and then drop it on another. All of this, with some UX considerations such as setting a custom drag image, updating the droppable element when something is dragged over it or when something is dropped on it.

When I was taking a deep dive into HTML5 drag-and-drop, I wanted to be able to wire-up a scenario where there were multiple “draggable” elements, and multiple “droppable” elements. So from a UX standpoint, my goals were:

  1. Any draggable could be dropped on any droppable
  2. Each droppable would change appearance when an element was dragged over it
  3. Each droppable would change appearance when an element was dropped onto it
  4. Each droppable would accept only one dropped element at a time
  5. The container that originally held the droppables would change appearance when empty
  6. The container that originally holds the droppables could accept any one or all of the droppables if they are dragged back to it

When I first attempted this, I got to a point where this all seemed like a lot of moving parts. Fortunately, a substantial portion of the challenge has been solved in parts I, II and III of this series, and I hope that if you have already read those articles, you have a solid understanding of how to do the following:

  1. Make an element draggable
  2. Set a custom drag element
  3. Make an element droppable
  4. Update the droppable when an element is dragged over it
  5. Update the droppable when an element was dropped onto it

So with that knowledge, our task list shrinks a bit:

  1. Any draggable can be dropped on any droppable
  2. Each droppable will accept only one dropped element at a time
  3. The container that originally held the droppables will change appearance when empty
  4. The container that originally held the droppables will accept any one or all of the droppables if they are dragged back to it

From here on, I will walk through the steps I took to accomplish these goals. There are probably other ways to go about solving these problems, but I am sharing the approach I took.

Task # 1: Any draggable can be dropped on any droppable

Well this was the easiest step. In parts I, II and III of this series, all of the JavaScript event binding was accomplished using classes instead of IDs. Because of this, adding more draggables and droppables in the HTML solved this problem. The existing JavaScript worked fine.

Task # 2: Each droppable will accept only one dropped element at a time

There are two things I needed to do in order to solve this problem: 1) create two separate “drop” event handlers, one for the multiple droppable HTML elements and another for the container that originally held the droppables; 2) in “drop” event handlers of the multiple droppables, check to see if the droppable element already has a child element.

Before I discuss the fix for task # 2, take a look at this JSFiddle link: http://jsfiddle.net/v9hawcof/5/

That link demonstrates the behavior that I do NOT want: more than one draggable can be dropped onto a droppable.

Base HTML

So in the code example above, we have the base HTML for the rest of the examples in this article. For brevity’s sake, I’ve stripped out all but the most essential areas of the markup so that you can focus on the technologies demonstrated in this article. When you view the page source for the final working example, you will see that there is more HTML, but it is for presentational purposes only.

Example # 1

Here is the JSfiddle link for Example # 1: http://jsfiddle.net/v9hawcof/6/

Now in Example # 1, I’ve added a new function called: “dropHandlerSingle”. This event handler is dedicated to the four light brown boxes at top (i.e. the “multiple droppables”). In the function I check to see if the droppable element has any children. If so, then I exit immediately. You may also notice that I trigger this custom event: “custom:dropEvent”. That will be explained shortly.

Task # 3: The container that originally held the droppables will change appearance when empty

Example # 2

Here is the JSfiddle link for Example # 2: http://jsfiddle.net/v9hawcof/7/

In Example # 2, you see the event handler for “custom:dropEvent”. The reason I used the setTimeout method, is because of timing challenges. When the drop event occurs, the DOM is not in the state needed in order to query it and figure out what is going on (i.e. which droppable elements have children). This event handler for “custom:dropEvent” will check each droppable element, and if it has no children, it removes the CSS class that gives it a “hasChildren” appearance (i.e. the background color changes from dark brown to light brown).

Task # 4: The container that originally held the droppables will change appearance when empty

Example # 3A

Example # 3B

Example # 3C

 Here is the JSfiddle link for Example # 3: http://jsfiddle.net/v9hawcof/8/

In Example # 3A, I bind an event handler for the container that originally held the droppables. In Example # 3B you’ll see that event handler: the “dropHandlerMultiple” function. The “dropHandlerMultiple” event handler does pretty much the same thing as the “dropHandlerSingle” event handler. The only difference is that the “dropHandlerMultiple” function does not check to see if it has children already. This is the critical step in accomplishing task # 4. In Example # 3B, you’ll see the code that tells the dragenter event handler to exit immediately if an element is dragged over the container that originally held the droppables. This is not a critical feature. I suppose I could have allowed the dragenter UX to apply to that container as well.

Here is the working example for this article: http://examples.kevinchisholm.com/html5/drag-and-drop/part-iv.html

Here is the JavaScript for this article’s working example: http://examples.kevinchisholm.com/html5/drag-and-drop/js/part-iv.js

Summary

As you can see, everything in this article is really a matter of personal choice. What I’ve done is detail how I decided to solve a particular UX challenge. Now how you approach this same set of tasks is completely up to you. I found that while attempting all of this, I learned a few things about HTML5 drag and drop. I hope you will too.

Getting Started with HTML5 Drag and Drop Part III: Setting a Custom Drag Image

HTML5

HTML5 LogoLearn how to set a custom drag image for a better drag and drop UX.

In previous articles of this series: “Getting Started with HTML5 Drag and Drop Part I: Introduction,” and “Getting Started with HTML5 Drag and Drop Part II: The dragenter and dragleave Events,” we covered the basics needed to implement HTML5 drag and drop. The second article focused on the UX for dropping a dragged element. In this article, we will cover a UX consideration for dragging: setting a custom drag image.

When dragging a draggable HTML element, the default drag image is the element being dragged. In most cases, this is probably just fine. But what about if you want to snazz-up the UX and specify a custom image for the drag operation?

Using an image that already exists on the page

When using an image that already exists in the page as your custom drag image, there are two restrictions:

  1. The image must exist in the DOM (i.e. it cannot have its “display” property set to “none,” or “visibility: hidden.”
  2. The image must be visible on the page (i.e. it must be visible without scrolling)

Example # 1

(for the base HTML, please refer to either Part I or Part II of this series; they both provide that markup).

Here is the JSfiddle link for Example # 1: http://jsfiddle.net/v9hawcof/3/

The setDragImage Method

In Example # 1, we have set the HTML5 logo as the custom drag image. We do this by using the document.getElementsByClassName method. Since this method returns an HTMLcollection, we reference the element by using the [0] property as we know we will only get one element back (yes, we could have used the document.getElementbyId method, but I wanted to keep the HTML clean).

There are a couple of drawbacks to this approach

  1. The HTML5 logo must be visible in the DOM, which is a bit restrictive
    Some browsers (e.g. Firefox) will display the image in its native size, whereas others (e.g. Google Chrome) might display it using the dimensions defined by its current CSS
  2. Using an external image for the custom drag image

Example # 2

Here is the JSfiddle link for Example # 2: http://jsfiddle.net/v9hawcof/4/

In Example # 2, we use an external image for our custom drag image. In this case it’s a silly image of Bart Simpson on his surfboard, but you can certainly use any image you desire. The advantage here is that we have much more control over the experience. We can use any image we like, and we don’t need to worry about whether or not the image we use is part of or visible in the DOM; it’s external to the DOM. Of course, you can use an image that already exists in the DOM, but you gain the greatest control when you create a new image, rather than use a reference to a DOM element.

Here is the working example for this article: http://examples.kevinchisholm.com/html5/drag-and-drop/part-iii.html

Here is the JavaScript for this article’s working example: http://examples.kevinchisholm.com/html5/drag-and-drop/js/part-iii.js

Summary

Setting a custom drag image may seem like icing on the cake, but it is not an uncommon case. In this article we discussed two options: using a reference to an existing image element in the DOM, as well as using an external image. There is no right or wrong answer as to which approach is best, but I hope this article has not only explained how to do this, but the pros and cons of each method.

Helpful Links for the HTML5 Drag and Drop setDragImage Method

https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#setDragImage.28.29

http://help.dottoro.com/ljdpgfkx.php

http://stackoverflow.com/questions/16894049/feature-detection-for-setdragimage-of-html5-drag-and-drop

Getting Started with HTML5 Drag and Drop Part II: The dragenter and dragleave Events

HTML5

HTML5 LogoGetting HTML5 drag and drop to work is a great start, but taking this to production requires certain UX considerations.

In the previous article of this series: “Getting Started with HTML5 Drag and Drop Part I: Introduction,” we covered the bare minimum code needed to make an HTML element draggable, and droppable onto another element. So, in Part II of this series, I will talk about two events that allow for better UX with regard to any element onto which you might drop something.

When I say: “…..any element onto which you might drop something,” I am referring to the fact that dragging something does not always mean that you will definitely drop it. In most drag and drop scenarios, you have one or more elements to drag, but also multiple places where you may drop them. Therefore, it is most often a good idea to give the user some indication that the element that they are dragging could be dropped in a particular location. Consequently, this involves setting up a hover-like behavior where the droppable element reacts to the fact that a draggable element has been dragged over it, or dragged away from it.

HTML Base

In the code example above, we have the base HTML for the rest of the examples in this article. For brevity’s sake, I’ve stripped out all but the most essential areas of the markup so that you can focus on the technologies demonstrated in this article. When you view the page source for the final working example, you will see that there is more HTML, but it is for presentational purposes only.

Example # 1

Here is the JSfiddle link for Example # 1: http://jsfiddle.net/v9hawcof/

The dragenter Event

In Example # 1A, we bind an anonymous function to the dragenter events of the droppable HTML element. In this event handler, we add the class: “dragEnter,” which changes the background color of that element. The reason for doing this is to tell the user: “If you want, you can drop the element that you are dragging.” But if you click the link above for the JSFiddle example, you’ll see that we have a problem. Although we add the dragEnter class when the user drags an element over the droppable element, we have not set a handler for when the user drags that element away; we can’t always assume that the user will drop the dragged element. So, we have to handle the case in which the user drags the element over the droppable element, but does not drop it, and then drags away.

Example # 2

The dragleave Event

Here is the JS fiddle link for Example # 2: http://jsfiddle.net/v9hawcof/1/

In Example # 2, we bind an anonymous function to the dragleave event of the droppable element. In that event handler, we simply remove the “dragEnter” class from the droppable element. If you click the jsFiddle link for Example # 2, you’ll see that the user experience is much better; when you drag the small blue box over the larger tan box, the droppable element turns green. So, if you choose not to drop the blue box, and drag it away, the droppable element turns back to tan.

Here is the working example for this article: http://examples.kevinchisholm.com/html5/drag-and-drop/part-ii.html

Here is the JavaScript for this article’s working example:
http://examples.kevinchisholm.com/html5/drag-and-drop/js/part-ii.js

Summary

It is hard to imagine a case in which you would not want to notify the user in some way of the various events that take place during a drag and drop operation. In this article, we focused on the case in which the user drags an element over a droppable one, but does not drop it, and then drags the draggable element away. By attaching event handlers to the dragenter and dragleave events, we have a window of opportunity in which the UI can be updated accordingly. How you prefer to handle the UX in this and similar cases is up to you, but it is an important area to consider.

Helpful Links for HTML5 Drag and Drop dragenter and dragleave Events

dragenter

https://developer.mozilla.org/en-US/docs/Web/Events/dragenter

dragleave

https://developer.mozilla.org/en-US/docs/Web/Events/dragleave

Easy Text Input “Hints” with the HTML <datalist> Tag

HTML5

HTML5 Logo
Provide helpful “hint” functionality for your text-inputs with just a little bit of hidden markup: the <datalist> element!

One of the newer HTML5 elements that I hear very little about is the Datalist tag. I’m a bit surprised by this because the datalist element is super-easy to implement and quite helpful.

In a nutshell, this tag provides easy “hint-like” behavior for text-inputs.

Surely we’ve all seen how some websites will provide “hints” as you type in a text-box. One of the most common examples, of course, is Google search. As you type, a list of words that match your input appear in and below the text box.

Most noteworthy: the HTML5 Datalist tag is not supported in Internet Explorer version 9 and below, nor Safari. But I think most would agree that this feature is an enhancement. So, you could implement it in your page, and consider it a “nice to have” if the user’s browser supports it.

Needless to say, any real-time “wildcard” implementation of this concept requires not only AJAX but some pretty serious back-end engineering that will provide useful hints quickly.

But what if you have a fairly strong idea of what the user “might” type. For example, let’s say that you prompt the user to enter the name of a European country in a text box. While that text box may allow any input, the user is likely to enter words such as “Austria”, “Belgium” or “Czech Republic”. So, why not add a little sugar to your page and “suggest” some of those words as they type?

Example # 1

Here in Example # 1, we have a very simple HTML form. Below that is the HTML5 Datalist element. That list is bound to the form by setting the form’s “list” attribute to the ID of the datalist (i.e. “euroCountries”).

Yes, it really is that simple.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1: http://jsfiddle.net/z99Jx/3/

How to Demo: When you view the JsFiddle.net link for Example # 1, you will see a text-input field in the output area. So, you just put your cursor in that input field and type any letter between “A” and “F”. And, of course, as you type, any country from the “euroCountries” list that has that letter in its name appears as a “hint”.

Oh my goodness… it really is that simple!

Example # 2

Now, here in Example # 2, there is code that you can run against this very web page. You may notice that in the upper-right-hand corner of this page, there is the text: “Search This Blog”. Below that is a text-input. If you type any letter between “A” and “F” right now, nothing happens.

Copy the code from Example # 2, paste it into your JavaScript console, and then execute it. Now, when you type any letter between “A” and “F”, any country from the “euroCountries” list that has that letter in its name appears as a “hint”.

Summary

In this article we learned about the new HTML5 Datalist tag. We also learned how this element can be used to provide “hints” for text input form elements. And finally, we learned how to bind that list to an input element, and set a list of options that will become the “hints”.

Helpful Links for the HTML5 Datalist tag

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

http://caniuse.com/datalist

http://www.htmlgoodies.com/html5/markup/whats-new-in-html5-forms-the-datalist-control.html#fbid=NYUB4nW2C7h

http://www.quackit.com/html_5/tags/html_datalist_tag.cfm

http://webdesign.tutsplus.com/tutorials/introducing-the-html5-datalist-element–webdesign-9888

http://davidwalsh.name/datalist

Creating an HTML Option Element Using the JavaScript Option() Constructor

JavaScript

JavaScript LogoThe little-known JavaScript Option() constructor allows you to avoid the verbose syntax of creating DOM elements

We all love jQuery. Among the many awesome qualities of this library is the ability to easily create DOM elements and place them in the document without the normally verbose syntax of native JavaScript.

But there is a little-known feature of JavaScript that allows you to create option elements with fairly minimal effort. This feature is the Option() constructor. The syntax is simple:

  1. Get a reference to a form element
  2. Instantiate the constructor and associate the returned object with the form element
  3. During instantiation, pass-in the following arguments: 1) the text shown in the page [string], 2) the value of the control [string], 3) if it is the default selection [true/false] and if it is selected [true/false]

Example # 1

 

In Example # 1, we have a simple form that includes a select control. In the markup there are three options: “Monday”, “Tuesday” and “Wednesday”. When the JavaScript runs, the following actions take place:

  1. We get a reference to the select controls (“w”)
  2. We delete all of the option elements (w.length = 0)
  3. We create an array of objects, each with two properties (“d”)
  4. We loop through the array and for each array element, dynamically create a new select element, using the object’s “text” and “val” properties. In each case the last two arguments: “false”,”false” mean that this new element will not be the default, nor will it be selected.

And that’s it!

Summary

The little-known Option() constructor can be used to create new HTML option elements. So, depending on how you choose to approach this, you can write some pretty efficient code that side-steps the normally verbose syntax of document.createTextNode(), document.createElement(), and document.appendChild() methods.

Helpful Links for the JavaScript Option() constructor

http://www.coderanch.com/t/120551/HTML-CSS-JavaScript/Option-Constructor

http://www.devguru.com/technologies/ecmascript/quickref/option.html

http://msdn.microsoft.com/en-us/library/ie/dd757810(v=vs.85).aspx

Building Dynamic HTML Markup with JavaScript – the Basics

JavaScript

JavaScript LogoWhen you need to iterate over a data set, and build markup using its elements, there are a few techniques that make this a snap

Sometimes you may need to build markup and insert it into the page, but perhaps you do not know what that markup will be. Actually, you would probably know most of what will happen: you have some markup that needs to be repeated one or more times, and in each iteration, the text in certain elements will change. A typical scenario is one in which you have multiple records in a data set, and you need to create a series of elements that will be similar, but each row in the data set will have it’s own copy of the markup and display its values. Same markup, but unique values with each iteration.

Example # 1

 

In Example # 1, we first created our data set (the variable “arr”), which is a JavaScript array. Each element of the array is an object literal, containing three fields. We then proceed to loop through all the elements of the array and for each one, we create a form. In each form, we mix the markup (which is the same with each iteration), but mix in the values from the data set so that when finished, each element in our data set has its own HTML form (think of it as rows in a table or records in a database). When we are finished creating the markup, we simply use the jQuery .html() method to insert our markup into the DOM, using the ID of a specific HTML element.

Two Quick Notes:

Variable Declarations – When declaring multiple variables, keep in mind that you can do so with one “var” statement, and separate each variable name with a comma. This makes things a bit easier to read and some argue that it is faster.

String Concatenation – Instead of one insanely long string, you can use the “+” operator, and break your assignments into multiple lines. Although this is JavaScript, it makes it look a bit more like actual markup.

Summary

There are, of course, much more elegant ways to do this; John Resig’s JavaScript Micro-Templating technique is a cool example. And there are plenty of others out there.  Here, I’ve simply covered the basic concept of working with data, and creating HTML on the fly to present that data in the page, regardless of the amount of data, or values it contains.

Helpful links for building dynamic HTML markup with JavaScript

http://markalexanderbain.suite101.com/an-introduction-to-dynamic-html-with-javascript-a74777

http://www.scriptingmaster.com/javascript/outputting-dynamic-HTML.asp

http://stackoverflow.com/questions/6106402/php-vs-javascript-for-dynamic-html-pages