Custom JavaScript

Custom JavaScript is for experienced developers who want to add small new features to their website.

These tutorials are intended for people who know a little JavaScript.

When using jQuery, please use "jQuery" instead of "$".

Do not insert jQuery by yourself using <script src="jquery.js"></script>", because jQuery is already included. If you insert jQuery another time, this will cause bugs.

You can put all of your custom JavaScript into "Lay Options" → "Custom CSS & HTML" → "Custom <head> content". Don't forget to wrap your JavaScript with <script> … </script>.

"Lay Options" &rarr "Custom HTML & CSS" → "Custom head content"

Newpage Events

Because a Lay Theme website loads its content via ajax you can't use jQuery(document).ready(…) to execute your js because the ready event only fires once when the website loads the first time.

Instead, use the event "newpageshown". It will trigger when a new page has rendered.

window.laytheme.on("newpageshown", function(){
});

You can do things like:

window.laytheme.on("newpageshown", function(){
	var slug = jQuery("body").attr("data-slug");
	var id = jQuery("body").attr("data-id");
	var type = jQuery("body").attr("data-type");
	if( slug == "about" ) {
		alert("Hey Cutie!");
	}
});

In the following example, a random background color out of an array of predefined colors is set for every page.

var colors = ["#fff", '#000', '#f0f', '#0ff', '#00f', '#ff0', '#0f0']
window.laytheme.on("newpageshown", function(){
	var ix = getRandomInt(0, colors.length);
	var color = colors[ix];
	jQuery('body').css('background-color', color);
});

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
// Returns a random integer between min (included) and max (excluded)
function getRandomInt(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min)) + min;
}

Binding Click Events

Let's assume you gave multiple elements on multiple pages a class of clickme in the Gridder. You did that by right clicking the elements and clicking "Set HTML class and id".

Now you want something to happen every time someone clicks that element. The easiest way to attach an event handler function to .clickme is to use jQuery's "on". We are using a so called "delegated" event handler:

jQuery(document).on("click", ".clickme", function(event) {
	console.log("yay!");
});

If we would bind the .clickme elements directly like jQuery(".clickme").on("click", …), that wouldn't work because the content of a Lay Theme website is loaded via ajax.

You shouldn't wrap this into a "newpageshown" event, it works fine like that.