Reputation: 21
When I have the following search parameter in the URL ?lname=lname
, I want to apply the following CSS:
.fname {
display: none;
}
.lname {
display: block;
}
<div class="fname">
<input id="userInput" class="form-control" placeholder="Enter Your Name">
</div>
<div class="lname">
<input id="userInput" class="form-control" placeholder="Enter Your Name">
</div>
The current CSS code looks like this:
.lname {
display: none;
}
Upvotes: 2
Views: 2859
Reputation: 91
You can use URLSearchParams to get parameters from URL, and then add CSS code according to your parameters
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('lname');
if(myParam !== null){
var styles = `
.lname{ display: none; }
}
var styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = styles
document.head.appendChild(styleSheet)
Upvotes: 1
Reputation: 450
Prefer using JQuery .
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
For Url parsing see this as a reference
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
Use this method to retrieve the parameters
var getUrlParameter = function getUrlParameter(a) {
var d = window.location.search.substring(1),
c = d.split("&"),
e, b;
for (b = 0; b < c.length; b++) {
e = c[b].split("=");
if (e[0] === a) {
return e[1] === undefined ? true : decodeURIComponent(e[1])
}
}
};
Then use a simple check and apply css using JQuery
if(getUrlParameter("lname") === 'lname'){
$(".fname").css({display:'none'});
$(".lname").css({display:'block'});
}
Upvotes: 0