skip to Main Content

I have a question, i wanted to know if there is a way to call a specific function if a specific page URL is opened?

  • #shop_modal is in http://myurl/liste-boutique.php
  • #dep_modal is in http://myurl/index.php

Right now, i have Error when i try to open the #dep_modal because JS cant find #shop_modal on that page same page, so it does not execute below that.

I think AJAX can help figuring this out, otherwise i will have to split the code in 2 JS files, which i don’t want to

const new_shop = $("#new_shop")[0];
const save_shop = $("#shop_form")[0];
const close_shop_modal = $("#close_shop_modal")[0];


const new_departement = $("#new_dep")[0];
const save_departement = $("#dep_form")[0];
const close_dep_modal = $("#close_dep_modal")[0];

// I want this to be called if the URL is http://my-URL/liste-boutique.php
new_shop.addEventListener('click', function(){
    $("#shop_modal")[0].style.visibility = "visible";
})

// I want this to be called if the URL is http://my-URL/index.php
new_departement.addEventListener('click', function(){
    $("#dep_modal")[0].style.visibility = "visible";
})

i need to ask question, but i don’t know what to change here
Thanks again !!

2

Answers


  1. You can check window.location.href. E.g.

    if (window.location.href === 'http://my-URL/liste-boutique.php') {
        new_shop.addEventListener('click', function(){
            $("#shop_modal")[0].style.visibility = "visible";
        });
    }
    
    Login or Signup to reply.
  2. Instead of checking the url, check if the element you want to find is on the page:

    var $new_shop = $("#new_shop");
    if ($new_shop.length > 0) {
        var new_shop = $new_shop[0];
        new_shop.addEventListener('click', function(){
            $("#shop_modal")[0].style.visibility = "visible";
        })
    }
    

    (I’ve used $ prefix on $new_shop to show it’s a jquery object just for clarity)

    Or, using your code as-is:

    var new_shop = $("#new_shop")[0];
    if (new_shop != undefined) {
        new_shop.addEventListener...
    

    Alternatively, if you use jquery, you don’t need to worry about it as it will automatically not apply if the element doesn’t exist:

     $("#new_shop").click(() => { $("#shop_modal)").fadeIn(); });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search