-1

I have two files index.php and settings.php. On index.php there is a button which redirects the user to settings.php on click.

<div id="settings">
    Settings
</div>

<script>
$("#settings").on
(
    "click",
    function()
    {
        window.location.href = "settings.php";
    }
);
</script>

There is also a button on settings.php which redirects back to index.php again on click.

<div id="menü">
    Menü
</div>

<script>
$("#menü").on("click", redirect("index.php"));

function redirect(url)
{
    window.location.replace(url);
}
</script>

But if i click on the buttons "Settings" then settings.php is loading and i get instantly redirected to index.php again.

However, if i use this code, then it does not redirect instantly:

$("#menü").on("click", function() { redirect("index.php");});

Why do i always need to wrap everything in function() if i use such events?

Black
  • 15,426
  • 32
  • 140
  • 232
  • 1
    `$("#menü").on("click", redirect("index.php"));` is instantly triggering that function yes. So you either need to wrap it in `function() { ..}`, or you could do `$("#menü").on("click", {url: "index.php"}, redirect);` and read out the arguments passed to your `redirect` function. – putvande May 03 '16 at 09:29
  • 1
    A simple link customized by CSS would do the same much more native, no need for any script. Do things as simple as possible. And why a function? The `on` method is declared to accept a callback function als 2nd argument. – Quasimodo's clone May 03 '16 at 09:33
  • 1
    You could actually make a function that makes redirect functions for you. LOL `function redirectTo(url) { return function() {redirect(url);};}` And use it like this `$('blah').click(redirectTo('index.php'))` – Yury Tarabanko May 03 '16 at 09:33
  • Cool, thanks for the tip @YuryTarabanko – Black May 03 '16 at 09:36
  • Nice trick @putvande, but how do i access the params in the function? With $1, $2 ? – Black May 03 '16 at 09:40
  • 1
    I believe it is `function redirect(event){ var url = event.data.url; }`, so whatever you pass in as arguments inside the event you can retrieve via `event.data`. – putvande May 03 '16 at 10:04
  • Yes it works like this @putvande, thank you :) – Black May 03 '16 at 10:44
  • Possible duplicate of [Pass a JavaScript function as parameter](http://stackoverflow.com/questions/13286233/pass-a-javascript-function-as-parameter) – Mogsdad May 11 '16 at 14:08

1 Answers1

1

The second parameter to .on() function should be either callback function or anonymous function. So, in your case the second parameter is a function call and so it will directly call the function without waiting for the click event.

Karthik M R
  • 970
  • 1
  • 7
  • 12