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.
- Replace
your_query_arg
with the query arg that you are checking for. - Use your own message.
- 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">⊗</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.
Questions and Comments are Welcome