Vanilla JavaScript functions

This blog post was written by Nick McBurney and published 20th April 2016

I initially built this website using jQuery to provide DOM manipulation but after running speed tests on my site I realised JQ was one of the main things slowing my site down, I decided to remove jQuery and convert my functions to vanilla JavaScript.

Ive listed my vanilla JS functions below (with demos), if you’re thinking of ditching jQuery then hopefully you’ll find them useful.

Vanilla JS functions:

  1. Wrap first word of headings in span tag
  2. Lazy load images
  3. Parallax background image
  4. Move element depending on screen width
  5. Add / remove class on click
  6. Sticky navigation on scroll

Wrap first word of headings in span tag

See demo here: http://codepen.io/NickMcBurney/pen/wGgqNY

// WRAP FIRST WORD OF <h> ELEMENT IN SPAN
function firstWord(){
	// get heading elements
   var $headings = document.querySelectorAll("h1, h3, h3");
	
	// run through each heading tag and insert spans
	for (var i = 0, len = $headings.length; i < len; i++) {
		console.log($headings[i].children.length)
		// if has child or has class X
		if ($headings[i].children.length < 1 && !$headings[i].classList.contains("blue")) {
			// set new text variable
			var niceText = $headings[i].textContent;	
			
			// set opening / closing spans
			var openSpan = '<span>', 
				 closeSpan = '</span>';

			// make the sentence into an array
			niceText = niceText.split(' ');

			// add open span to the beginning of the array
			niceText.unshift( openSpan );

			// add closing span as the 3rd value in the array
			niceText.splice( 2, 0, closeSpan );					

			// turn it back into a string 
			niceText = niceText.join(' ');				

			// append the new HTML to the header
			$headings[i].innerHTML = niceText;
		}
	}
}

// check document is ready
var domReady = function(callback) {
	document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};

// on document ready 
domReady(function() {
	// run firstWord function	
	firstWord()
});

Original wrap first word jQuery function

// JQUERY VERSION
var headings = "h1, h2, h3"

$(headings).each(function(){
	if ($(this).children().length < 1 && !$(this).hasClass("no-first-word")) {
		// Get the text of the element I'm after
		var firstword = $(this).text(),
			 openSpan = '<span>', closeSpan = '</span>';

		// Make the sentence into an array
		firstword = firstword.split(' ');

		// Add span to the beginning of the array
		firstword.unshift( openSpan );

		// Add as the 4th value in the array
		firstword.splice( 2, 0, closeSpan );					

		// Turn it back into a string
		firstword = firstword.join(' ');					

		// Append the new HTML to the header
		$(this).html(firstword);
	}
});

Lazy load images

See demo here: http://codepen.io/NickMcBurney/pen/RagyeW

// LAZY LOAD FUNCTION
function lazyLoadImages(){
	// get all images with 'lazyload' class
	var $images = document.querySelectorAll("img.lazyload");
	
	// if there are images on the page run through each and update src
	if($images.length > 0) {
		for (var i = 0, len = $images.length; i < len; i++) {
			
			// get url from each image
			var image_url = $images[i].getAttribute("data-delaysrc");
			// set image src 
			$images[i].src = image_url;
			
			// debugging
			var $lognumber = i + 1;
			console.log("Image No." + $lognumber + " loaded");
		}
	}
	console.log("Images loaded")
}


// PAGE LOADED
window.addEventListener('load', function() {
	console.log("Page loaded");
	// run lazy load function
   lazyLoadImages();
}, false);

Original lazy load images jQuery function

// LAZY LOAD FUNCTION
function lazyLoadImages(){
	// get all images with 'lazyload' class
	var $images = $(".lazyload");
	
	// if there are images on the page run through each and update src
	if($images.length > 0) {
		$($images).each(function(i) {
			var image_url = $(this).attr("data-delaysrc");
			$(this).prop("src", image_url)
			
			// debugging
			var $lognumber = i + 1;
			console.log("Image No." + $lognumber + " loaded");
		});
	}
	console.log("Images loaded")
}


// PAGE LOADED
$(window).load(function(){  
	console.log("Page loaded");
	// run lazy load function
   lazyLoadImages();  
});

Parallax background image

See demo here: http://codepen.io/NickMcBurney/pen/vGZryy

// PARALLAX BACKGROUND IMAGE
function parallax() {
	var $slider = document.getElementById("background-element");

	var yPos = window.pageYOffset / $slider.dataset.speed;
	yPos = -yPos;
	
	var coords = '0% '+ yPos + 'px';
	
	$slider.style.backgroundPosition = coords;
}

window.addEventListener("scroll", function(){
	parallax();	
});

Original parallax background image jQuery function

// PARALLAX BACKGROUND IMAGE
function parallax() {
	var $slider = $("#slider");
	
	// scroll amount / parallax speed
	var yPos = -($(window).scrollTop() / $($slider).data('speed'));

	// background position
	var coords = '0% '+ yPos + 'px';

	// move background image
	$($slider).css({ backgroundPosition: coords });
}
$(document).ready(function(){
	parallax()
});

Move element depending on screen width

See demo here: http://codepen.io/NickMcBurney/pen/JXEJaq

// MOVE ELEMENT DEPENDING ON SCREEN WIDTH
function movePosition(){
	// set element variables
	var $newContainer = document.getElementById("intro-section");
	var $originalContainer = document.getElementById("originalContainer");
	var $elementToMove = document.getElementById("elementToMove");
	
	// get window width
	var $windowWidth = document.documentElement.clientWidth;
	// positioning if statement
	if($windowWidth < 800){
		// if below 800px insert before the second child element
		$newContainer.insertBefore($elementToMove, $newContainer.childNodes[2])
	} else {
		// if above 800px move to original location
		$originalContainer.appendChild($elementToMove);
	}
}

// check document is ready
var domReady = function(callback) {
	document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback);
};

// on document ready 
domReady(function() {
	// run move function	
	movePosition()
});

// on window resize
window.onresize = function(event) {
	// run move function
   movePosition()
};

Original move position depending on width jQuery function

// MOVE ELEMENT DEPENDING ON SCREEN WIDTH
function movePosition(){
	// set element variables
	var $introPosition = $("#intro-section h1");
	var $image = $("#image");
	var $imageHold = $("#imageHold");
	
	// get window width
	var $windowWidth = $(window).width();
	// positioning if statement
	if($windowWidth < 800){
		// if below 800px insert after the title and above paragraph
		$image.insertAfter($introPosition)
	} else {
		// if above 800px move into imageHold (sidebar loctaction)
		$imageHold.append($image);
	}
}

$(document).ready(function(){
	movePosition()
})

Add / remove class on click

See demo here: http://codepen.io/NickMcBurney/pen/QNgBEe

// ADD / REMOVE CLASS ON CLICK
// button element variable
var $button = document.querySelector("button");

// on click event
$button.addEventListener('click', function () {	    
    if($button.classList.contains("selected")){
	    // if has 'selected' class remove class
	    $button.classList.remove("selected"); 
	} else {
		// otherwise add 'selected' class
		$button.classList.add("selected"); 
	}	
});

Original add/remove class jQuery function

// JQUERY VERSION
var $button = $("button")

$($button).on("click", function(){
	if($(this).hasClass("selected")) {
		$(this).removeClass("selected")
	} else {
		$(this).addClass("selected")
	}
})

Sticky navigation on scroll

See demo here: http://codepen.io/NickMcBurney/pen/QNdOeQ

// sticky nav on scrolled to
// set nav variable
var $nav = document.getElementsByClassName("main-nav");

console.log($nav[0]);
// get nav position from top of window
var posTop = $nav[0].getBoundingClientRect().top;

// sticky function
window.addEventListener("scroll", function(){
	var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
	
	// run function
	stickyNav();
});

window.addEventListener("resize", function(){
	// set nav variable
	$nav = document.getElementById("navigation");
	// check nav top position
	posTop = $nav[0].getBoundingClientRect().top;
});

// STICKY NAV FUNCTION
function stickyNav(){
	// get scroll amount as varible
	var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

	// if scrolled to nav make sticky
	if (scrollTop > posTop) {
		// add sticky class
		$nav[0].className = "main-nav sticky";
	} else {
		// remove sticky class
		$nav[0].className = $nav[0].className.replace("sticky","");
	}
}

Original sticky navigation jQuery function

// JQUERY VERSION
// get navigation
var $nav = $('nav'),
	 // get nav position from top of window
	 posTop = $nav.position().top;

$(window).resize(function() {
	posTop = $nav.position().top;
});

// check position
$(window).scroll(function () {
	var y = $(this).scrollTop();
	// WHEN scrollTop() REACHES TOP OF NAVIGATION ADD .fixed
	if (y > posTop) { $nav.addClass('sticky'); }
	// IF scrollTop() IS ABOVE NAVIGATION REMOVE .fixed
	else { $nav.removeClass('sticky'); }
});

Let me know what you think

Your email address will not be published. Required fields are marked *