Pure JavaScript – Show Message If a URL Query Arg is Set, Then Remove It

This lets you show a message if a specific URL query arg is present on the current page, then the visitor can click to close the message, and the query arg will also go away. This example uses pure JavaScript, no jQuery.

The HTML

<span id="slug-success"></span>

The CSS

#slug-success {
    color: #4F8A10;
    background-color: #DFF2BF;
    display:block;
    padding-left:4px;
    padding-right:4px;
}
#slug-close-msg {
    font-size: 28px;
    float: right;
    margin-top: -10px;
    cursor: pointer;
}

The JavaScript

Only edit lines 1 – 3.

  1. Replace your_query_arg with the query arg that you are checking for.
  2. Use your own message.
  3. Replace ‘slug-success’ if you need to, but this must match the ID in the HTML span element above.
var queryArg = 'your_query_arg';
var msg = 'This is the message. Replace this with your own message.';
var element = document.getElementById('slug-success');

// ----  No need to edit past this point ----

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if(pair[0] == variable){return pair[1];}
	}
	return(false);
}

var success = getQueryVariable(queryArg);

if ( success ) {
	
	element.innerHTML = '<span id="slug-close-msg">&#8855;</span>' + msg;

	document.getElementById('slug-close-msg').addEventListener('click', function() { 

		// remove the quer arg
		var clean_uri = location.protocol + "//" + location.host + location.pathname;
		window.history.replaceState({}, document.title, clean_uri);
		
		// close the message
		element.style.display = 'none';

	}, false);
}

Notes

When the user clicks to close the message, any URL query args will be removed, not just the one that was searched for.

See more:

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]