skip to Main Content

I am loading a form into a page via javascript and I only want to show this form when the url contains a specific expression like: /home.
The form loads for the main page and all sub pages and should only be shown for a sub page containing the above expression, while hidden for all other cases.
I am relatively new to javascript and this problem really strikes me, so any help would be welcome and greatly appreciated.

Best,
Christian

Any help to get started is welcome

2

Answers


  1. You can check the URL of the page and then display the form based on the specific conditional expression. I’ll share a simple example using JavaScript for your trouble.

    HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Your Page Title</title>
    </head>
    <body>
        <!-- Your page content -->
    
        <div id="formContainer" style="display: none;">
            <!-- Your form goes here -->
        </div>
    
        <script src="your-script.js"></script>
    </body>
    </html>
    

    JS

    document.addEventListener("DOMContentLoaded", function () {
        // Check if the URL contains the specific expression
        var urlContainsExpression = window.location.pathname.includes("/home");
    
        // Get the form container element
        var formContainer = document.getElementById("formContainer");
    
        // Show or hide the form based on the URL condition
        if (urlContainsExpression) {
            formContainer.style.display = "block";
        } else {
            formContainer.style.display = "none";
        }
    });
    

    This code uses the window.location.pathname property to get the current page’s URL path. It then checks if this path contains the specified expression ("/home") using the includes method. Depending on the result, it sets the display style property of the form container to either "block" (to show) or "none" (to hide).

    Login or Signup to reply.
  2. You can hide element when url does not include ‘/home’ like this

    document.addEventListener("DOMContentLoaded",() => {
      const currentUrl = window.location.href;
      if (currentUrl.includes("/home")) {
        showForm();
      } else {
        hideForm();
      }
    });
    
    const showForm = () => {
      const form = document.getElementById('form-id');
      if (form) {
        form.style.display = 'block';
      }
    }
    
    const hideForm = () => {
      const form = document.getElementById('form-id');
      if (form) {
        form.style.display = 'none';
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search