Tag Archives: javascript

JavaScript: Check if an Object Property exists Programming 23 FEB 2016

A lot of warnings in code that I have to maintain often stem from the fact that the initial developer never bothers checking whether or not a given property of an object exists before trying to use it.

We’ve got a couple of options available to us to check whether or not a property actually exists in a given object, including the simple checking on whether or not the typeof returns ‘undefined’, or even using a basic in to check.

In practice (checking if property name exists in object user):

//Example of 'typeof' check - 
//Note: Of course, this could provide a false positive if the property value is actually set to 'undefined'
if (typeof user.name === 'undefined') {
console.log('name property is missing');
}

//Example of 'in' check
if (!('name' in user)){
console.log('name property is missing');
}

A better, although slightly more costly (in terms of speed) check is to use the hasOwnProperty() method, which checks if the object on its own (not through one of its ancestors) has the given property or not.

In practice:

//Exammple of 'hasOwnProperty' check
if (!user.hasOwnProperty('name')) {
    console.log('name property is missing');
}

Of course, you probably should probably also check that the actual object itself exists first!

chimpanzee using a laptop to fix a problem

jQuery UI Slider Pips: Enhancing jQuery Sliders with Labels and Pips Software & Sites 25 MAR 2015

The jQuery UI user interface library, built on top of the excellent jQuery JavaScript library, includes a pretty neat slider control that allows users to select a numeric value by dragging a handle with either the mouse or keys.

However, it is missing a few important things if you want to start using sliders in a little more user friendly, complex way – what it needs is pips (point dashes to indicate length/distance/value range) as well as labels.

Which is exactly why Simon Goellner (aka slimeydotme, or more accurately, slimey.me) went ahead and created the fantastic jQuery UI Slider Pips plugin to, as he puts it:

A plugin to extend the jQuery UI Slider control. This plugin adds “pips” to the slider for visual aid, as well as “labels” which the developer can customize.

It is full featured, well written, and particularly easy to add to any existing slider declaration. More importantly, it is very configurable, making it a must if you want to implement sliders in a more meaningful way.

Installation is as easy as downloading both the .js and .css files, and then running the code is little more than:

<div class="slider"></div>
$(".slider").slider().slider("pips");

(The default way to use the plugin – as shown above – is to call the pips method on an initialised slider. This will add the markers along the slider, and place the min/max values to the beginning/end of the slider).

Well worth a look in other words.

jquery ui slider pips example

Related Link: http://simeydotme.github.io/jQuery-ui-Slider-Pips/

jQuery UI Autocomplete: How to clear the Search Text after Selection Programming 24 MAR 2015

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. One of the useful widgets in the collection is the Autocomplete widget, which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Easy to implement, works like a charm, the question then is how does one clear the search text after the user makes a selection from the autocomplete list?

Simply setting the value to ” in the select event function declaration won’t work out of the box, because the select event occurs before the field is actually updated – in other words, your change will be lost when the textbox is updated. To prevent this from happening, you essentially need to cancel the event to stop it from running to completion – in other words, return false.

So in practice, your declaration should look like this:

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
$(document).ready(function(){
var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags,
      select: function(event, ui) {
          alert(ui.item.value);
          this.value = "";
          return false;
      }
    });
});

And that is all there is to clearing the search term from the Autocomplete box after a user selects something!

pink convertible bug - volkswagen beetle

Related Link: http://jqueryui.com/autocomplete/

jQuery: How to Break Out of an Each Loop Programming 16 MAR 2015

The ever so useful jQuery javascript library has a homegrown loop function entitled .each(), which allows you to iterate over a jQuery object, and at the same time execute a function for each matched element.

Very useful indeed.

However, sometimes you might need to break out of a loop early (for example, maybe your loop has the potential of carrying on forever – which obviously is not so great for your patiently waiting audience) – and this is how you do it:

To break a $.each() loop, you have to return false in the loop callback function. (Returning true is equivalent to continue in a normal loop, in other words it skips to the next iteration – exactly the opposite of what you are trying to achieve!)

An example:

$(document).ready(function(){
$('.lotsOfTheseClassesExist').each(function(i, item){
alert($(item).prop('id'));
return false; //exits the loop
});
});

So your break statement for a jQuery each() loop is literally return false.

girl in pink high heels and a black leotard with lots and lots of shiny hula hoops

jquery logo

Related Link: http://api.jquery.com/each/

jQuery: How to Check if an Element has Class ‘X’ or ‘Y’ Programming 15 MAR 2015

If you find yourself needing to check whether or not a particular HTML element has a specific class currently assigned to it, you’ll be pleased to know that the awesome jQuery javascript library has you covered with their ever so useful .hasClass function.

This function determines whether any of the matched elements are assigned the given class, returning true if the searched for class is in fact assigned to an element – regardless of whether or not that element has more than one class assigned to it. (Remember, HTML allows elements may have more than one class assigned to them – separated by a space in HTML notation.)

An example:

<div id="mydiv" class="foo bar"></div>
$( "#mydiv" ).hasClass( "foo" ); //returns true
$( "#mydiv" ).hasClass( "quu" ); //returns false

In other words, no need for splitting an element’s class attribute and then looping through the strings just to see if a particular class exists any more!

a lady with class - audrey hepburn

jquery logo

Related Link: https://api.jquery.com/hasclass/

How to Trigger a jQuery UI Accordion Click Action Tips, Tricks and Tutorials 30 AUG 2013

jqueryui logoThe Accordion jQuery UI widget is a great way to present lots of data in a limited space through the use of collapsible panels.

If your panels are fairly large, or perhaps you have a quite a few of them in the accordion, then sometimes it would be nice to use a row of central links or buttons to trigger the collapsible pattern, basically saving the user the effort of scrolling all the way down the page to get to the last panel.

In other words you want to programmatically click a panel heading in order for it to show.

Thankfully, jQuery UI’s accordion API makes it a pretty simple task – essentially you just need to set the ‘active’ option to the desired index of the zero-indexed list of panels. In other words, if you have three panels and you want to open up the second panel, then you’ll need to set the active option to 1.

In practice – First, the HTML:

<div style="text-align:center;padding:5px;"><span class="activelink link">Active</span> | <span class="internallink link">Internal</span> | <span class="closedlink link">Closed</span></div>
<div id="accordion">
<h3>Active</h3>
<div>Bla bla bla 1</div>
<h3>Internal</h3>
<div>Bla bla bla 2 </div>
<h3>Closed</h3>
<div>Bla bla bla 3</div>
</div>

Now the JavaScript:

$(document).ready(function() {
                var myaccordion = $('#accordion').accordion();

                $('.activelink').click(function() {
                    $('#accordion').accordion("option", "active", 0);
                });
                $('.internallink').click(function() {
                    $('#accordion').accordion("option", "active", 1);
                });
                $('.closedlink').click(function() {
                    $('#accordion').accordion("option", "active", 2);
                });
            });

Solved.

Related Link: http://jqueryui.com/accordion/

How to Generate a Random Number in JavaScript Programming 13 AUG 2013

javascript logoGenerating a random number in JavaScript is a relatively easy thing – we simply made use of JavaScript’s built in random() function, part of the JavaScript Math object.

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

If we then combine this method with the floor() method (also from the JavaScript Math object – Give x, returns x, rounded downwards to the nearest integer), then it becomes trivial to quickly generate a random number.

For example:

//Return a random number between 1 and 10:
Math.floor((Math.random()*10)+1);

//Return a random number between 1 and 50:
Math.floor((Math.random()*50)+1);

Simple and effective.

jQuery: How to Test if a div is Visible Programming 17 JUL 2013

jquery-logoThe wonderful jQuery library actually makes it pretty easy for us to test whether or not a div (or pretty much any other element for that matter) is currently visible, by providing us with a ‘:visible’ selector.

Basically elements are considered visible by jQuery if they consume space in the document, meaning that visible elements have a width or height that is greater than zero. Combining this with the .is filter forms the basis for our test.

In practice:

//assuming a div with id "div1"
$('#div1').show();
alert ($('#div1').is(':visible')); //true
$('#div1').hide();
alert ($('#div1').is(':visible')); //false

Nifty. As always, play with around with it yourself in the awesome JSFiddle online JavaScript playground.

Javascript: How to Extract a Number from a String Programming 04 JUL 2013

javascript logoIn my web development work, I’m quite fond of using the trick of generating grouped elements by making sure their IDs all share a common number with a bit of unique text.

So for example I could have a set of elements with the IDs accordionheading1, accordionpanel1, accordiontext1 and accordionheading2, accordionpanel2, accordiontext2. Now in order for this to be useful, I need to be able to extract the number from these strings so that I can automatically guess an element’s associated partners, meaning that you now know exactly what is coming next:

One of the easier ways of extracting a number from a string using javascript is by making use of a bit of regex, utilizing the digit negated shorthand character class \D to do our dirty work.

In practice:

var element = 'accordion24paneldrop';
id = element.replace( /\D+/g, '');
alert(id); //24

Nifty.

Check it else for yourself using JSFiddle! (JS Bin is pretty cool too)