2

My problem is that if I execute this code in the browser console, it is working properly, the spans get changed according to the URL parameter given etc. But if I just load the page, I get the respective console logs but no spans are filled. Does anybody see a problem?

P.S. Window on load was a desperation move so don't judge me, it's optional.

EDIT: I should maybe mention that I come from Python programming so I might not understand certain things to do with JS... sry

jQuery Code:

function setSlogan(sloganText) {
   console.log(sloganText);
   $("#productLeadLogin").text(sloganText);
   $("#productLeadRegistration").text(sloganText);
}



const params = new URLSearchParams(window.location.search);

function chooseSlogan (){
    switch (params.get("product")) {
        case "...":
            console.log("Got ...");
            slogan = "to the ... services";
            console.log(slogan);
            setSlogan(slogan);
            break;
        default:
            console.log("defaulting");
            slogan = "to all your default services";
            console.log(slogan);
            setSlogan(slogan);
            break;
    }
}

$(window).on("load", chooseSlogan()); // it's called desperation

one of the spans to change:

<h6 class="font-weight-light">Sign In here to get access <span id="productLeadLogin"></span>.</h6>
BambCoder
  • 23
  • 4
  • 1
    You need to pass the _reference_ to your function object as callback parameter in `.on`, but you are _calling_ it directly in that place. Difference `foo()` vs `foo` – CBroe Feb 24 '20 at 14:26
  • 1
    Should be: `$(window).on("load", chooseSlogan);` – freedomn-m Feb 24 '20 at 14:29
  • @freedomn-m could you please post this as an answer so I can accept it? *Passing the function on load works!* Thanks! – BambCoder Feb 24 '20 at 14:32

1 Answers1

1
$(window).on("load", chooseSlogan());

You need to pass the reference to your function object as callback parameter in .on, but you are calling it directly in that place. Difference foo() vs foo.

So this part needs to be

 $(window).on("load", chooseSlogan);
CBroe
  • 91,630
  • 14
  • 92
  • 150