Get element’s tagname using DOM’s tagName property

A couple of weeks ago I posted how can you get an element’s tagname using jQuery’s .prop() method. A simpler alternative could be the below code :

See the Pen Get element’s tagname using DOM’s tagName property by John Tsevdos (@tsevdos) on CodePen

The .get() method (don’t confuse this method with the jQuery’s AJAX .get(), they are completely different) retrieves the DOM element and then we simply get it’s tagName property (and convert it to lowercase). We can even retrieve the DOM element from a jQuery array using the below syntax (without the .get() method) and have the exact same result.

See the Pen Get element’s tagname using DOM’s tagName property by John Tsevdos (@tsevdos) on CodePen

I believe that the above method is easier and faster than the previous one.

jQuery element’s tag name

Getting the selected element’s tag name is very easy in jQuery. Just use the below code.

See the Pen jQuery element’s tag name by John Tsevdos (@tsevdos) on CodePen

Keep in mind that by default the returned tag’s name is capitalized so if you want it lowercase you’ll need this :

See the Pen jQuery element’s tag name by John Tsevdos (@tsevdos) on CodePen

jPrefetch jQuery plugin

I just released jPrefetch a nice little jQuery plugin that makes HTML5 prefetching a bit easier. You can very easily use it for your current solution (static website or even CMS), just by including it and adding data-prefetch="true" to the link that you want to prefetch. You can also pass a url (string) in order to start prefetching the provided url, in case you are loading a page that doesn’t have any link with the data-prefetch attribute. jPrefetch will take care all the rest, and start adding the necessary markup (metatags) in order to allow prefetching in supported browsers (tested in Chrome and Firefox). As you can see, the use of this is very easy and elegant. The plugin was mainly inspired by these two excellent articles, Mastering HTML5 Prefetching and Prefetching with HTML 5 and jQuery.

Feel free to fork it, use it, whatever 😉

The get() method is not working! Well try eq()…

Every now and then, I come across the very same issue, so I decided to write a post about it. Many new JS developers are struggling to find out why the below code is not working when applying jQuery’s get() method :

See the Pen The get() method is not working! Well try eq()… by John Tsevdos (@tsevdos) on CodePen

The selector is correct, and if we remove the get() method, it magically works!

The answer is pretty obvious if you check get()‘s documentation. The get() method returns a DOM object, not a jQuery one! This means that you don’t have access to jQuery’s fun methods… If you want a similar method (that returns a jQuery object) try eq(), it works the exact same way.

jQuery lights off effect

I’ve been working on a “lights off” effect for videos the other day. Here’s a demo page (with the appropriate code) that I might turn into a proper plugin if there is enough interest. Enjoy…

$(document).ready(function(){
	
		// Build the link
		$('.lightsoff').append('<div class="lightsoffbtn"><a href="#">Lights Off</a></div>');
		
		// Prepare the overlay
		$('body').append('<div class="lightsoff-ovelay off" style="position:relative; z-index:1; display:none;">close</div>');
		
		// Variables
		var $overlay = $('.lightsoff-ovelay'),
			$containers = $('.lightsoff'),
			$lightsoffTrigger = $('.lightsoffbtn a');
	
			
		// LightsOff events
		$lightsoffTrigger.each(function(){
		
			// Variables
			var $container = $(this).parent().parent();
	
			// Apply some CSS
			$container.css({ 'position': 'relative' });
	
			$(this).click(function(e){
	
				e.preventDefault();
					
				if ( $overlay.hasClass('off') ) {
	
					$container.css({
						'z-index': 4000
					});
	
					$overlay.css({
						'position': 'fixed',
						'display': 'block',
						'text-indent': -99999,
						'background-color' : '#000000',
						'width': '100%',
						'height': '100%',
						'top': 0,
						'left': 0,
						'z-index': 3000,
						'opacity': 0.7,
						'cursor': 'pointer'
					});
	
					$overlay.removeClass('off').addClass('on').fadeIn();
	
				} else if ( $overlay.hasClass('on') ) {
					e.preventDefault();
					$containers.css({ 'z-index': 0 });
					$overlay.removeClass('on').addClass('off').fadeOut();
				}
			
			});
		
		});
		
		$overlay.click(function(e){
			e.preventDefault();
			$containers.css({ 'z-index': 0 });
			$overlay.removeClass('on').addClass('off').fadeOut();
		});
	
	});Check out this Pen!

jQuery window.onload equivalent

Last week a reader contacted me noting that my equal heights script was not working. When I took a closer look at his code, I found out that the reason for it not working correctly wasn’t my script but the way jQuery works! The normal jQuery behaviour is to run the code when the DOM is ready and won’t wait for images/graphics etc, to load. There are some cases though, that someone needs to run a piece of code after the entire page is fully loaded. You can achieve that with the code bellow :

$(window).load(function() {
	// When the entire page is fully loaded
	$('#content, #sidebar').equalHeights();
});Check out this Pen!

The elements that needed equal heights contain images, so the script was miscalculating the max-height value because it wasn’t getting the correct height of the images (since they were still loading). The above code will fix that, since it will load the script when the entire window is fully loaded (including images).

Keep in mind that this is an event handler method (a shortcut for .bind('load', handler) ) and has nothing to do with the ajax load() method.

Organizing jQuery Code

Organizing jQuery code is not easy. Up to now, especially on small/medium scale projects, I used to have a huge jQuery ready function and place all my code there. Some times if I needed to run something on specific elements I was just doing a quick test to check if the element was on the document.

$(document).ready(function(){
	//jQuery code...
	if ( $('.someClass').length ) { // if element exists then run the below code
		// Do something
	}
});Check out this Pen!

The above technique is not too bad, it works just fine for a small or medium sized site, but what happens with a larger site that uses heavy javascript code? The answer came from a presentation I watched recently (Simple JavaScript & CSS Management With Rack by Mr. Avand Amiri – I strongly encourage you to watch it as well). The solution is really clean and pretty smart. Just create a javascript file (actually you can break it to as many files as you want) that will hold all your main objects. Below is a very basic “Greetings” object.

var Greetings = {
	alertFn: function () {
		alert('OK');
	},
 
	john: {
		sayHelloToJohn: function() {
			alert ('Hello John!');
		}
	}
// do something else, etc.
}Check out this Pen!

At the example above the object “Greetings” contains two methods (functions). As you can see, I could go further and create nested objects with their own methods. The idea is to organize my methods as well as I can.

Then I only have to call them into our usual jQuery ready function like this.

$(document).ready(function(){
  Greetings.alertFn();
});
// or
$(document).ready(function(){
	Greetings.john.sayHelloToJohn();
});Check out this Pen!

Keep in mind that this way I can follow any code structure/organization I need, so for example I can follow my application’s controllers structure and naming convention, or whatever makes more sense for my app. This way we get a simple, more robust, well-organised jQuery code, and not the classic document ready soup…

A really simple “equal heights” method for jQuery!

Nothing special, a really basic “equal heights” method written in jQuery.

$.fn.equalHeights = function() {  
    var maxHeight = 0;  
    $(this).each(function(index){  
        var height = $(this).height();  
  
        if (maxHeight < height) {  
            maxHeight = height  
        }  
   });  
   $(this).height(maxHeight);  
}

$("ul li").equalHeights();Check out this Pen!

Then you just need to apply the method on the element you want using $("ul li").equalHeights();.

Convert a jQuery object to raw DOM object

There are two, easy ways to achieve this. The first one is simply by using the array [] notation directly on the jQuery object :

var myDiv = $('div')[0]; // myDiv is a raw DOM object  
myDiv.innerHTML = 'New Hello World text!'; // and we can do all the normal things with itCheck out this Pen!

The second one is by using the get method, the “core get” method, not the “AJAX get” one. The get method returns an array with the selected elements, and we can optionally pass an index number parameter to return the element we need.

var myDiv= $('div').get(0); // myDiv is again a raw DOM object  
myDiv.innerHTML = 'New Hello World text!'; // and we can do all the normal things with itCheck out this Pen!

Super easy, isn’t it?