Search code examples
javascriptjqueryfunctionswitch-statementlocation-href

jquery.tap run the function without event


function onHref(href){
    window.location.href = href;
}

When i run the code automatically get redirected to the last obj[key].link

switch ( obj[key].type ) {
        case 'href': //se href attribuisce link diretto alla pagina
            $(id).tap(onHref(obj[key].link));
            break;

Solution

  • Because you are invoking the function by adding () at the end of onHref.

    One solution is to use a anonymous function as the event handler then call onHref inside it

    $(id).tap(function () {
        onHref(obj[key].link)
    });
    

    Another option is to use Function.bind() to create a function reference like

    $(id).tap(onHref.bind(undefined, obj[key].link));