JavaScript is the most widely used scripting language on earth. Javascript can be used with Convert in a diversity of cases. This article is all about JS conditions examples that can be used targeting URLs, cookies, variables and others. The codes are from real use case scenarios.
Where Javascript can be implemented?
Basically everywhere, Goals, Audiences, Site Area, Experience, Variation and Project.
Examples:
Referral URL
// Matches
document.referrer == "YourURL.com"
// Is not
document.referrer != "YourURL.com"
//Contains
document.referrer.includes('somethingtocheck') == true/false
URL/Parameter/Query String
//Single condition
window.location.href.includes('yourstring') == true
//Multiple conditions using OR
window.location.href.includes('?yourstring') || window.location.href.includes('&yourstring') == true
//Multiple conditions using AND
window.location.href.includes('yourstring') && window.location.href.includes('yourstring2') == true
URL using Regex
//Starts with
window.location.href.match(/https?:\/\/(www.)?yourdomain.com\/(child\/child1\/child2)(|\/)(.*)/).length > 0
//Using wildcards (same as contains)
window.location.href.match(/(.*)\/(child\/child1\/child2)(|\/)(.*)/).length > 0
Cookies
//Cookie is present
document.cookie.indexOf('cookieName') > -1
//Cookie is not present
document.cookie.indexOf('cookieValue') > -1 == false
// Cookie is present and contains
document.cookie.indexOf('cookieName') > -1 && document.cookie.indexOf('cookieValue') > -1
Variables
//Variable is present
typeof yourvariable != 'undefined'
//Variable is not present
typeof yourvariable == 'undefined'
//Variable contains/not contains
yourvariable.includes('valuetocheck') == true/false
Elements
//Element is present
document.getElementById("intro") != null
document.getElementsByClassName("intro") != null
convert.$('.selector').length != 0
//Element is not present
document.getElementById("intro") == null
document.getElementsByClassName("intro") == null
convert.$('.selector').length == 0
Screen Size
screen.width == 1920
screen.height == 1080
Comments