2

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;
}
1
  • 1
    If there is some server side logic, you can define which css file is in your header based on query string. Then you dont have to wait for jquery/js script to load and exexute before the right styles are visible for the user. Commented Sep 4, 2020 at 5:37

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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'});     
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.