0

I want to implement a function into the $(document).ready(xx) block.

It should look like this but doesn't work:

$(document).ready(function () {
    function navTo(target) {
        if (target === 'into.html') {
            window.location.href = 'into.html';
        }
        else if (target === 'index.html') {
            window.location.href = 'index.html';
        }
    }

    window.init = changeColor();

    function changeColor() {
        document.getElementById("url").style.color = "#000000";
    }
});

if I do like this, it works:

$(document).ready(function () {

    window.init = changeColor();

    function changeColor() {
        document.getElementById("url").style.color = "#000000";
    }
});


function navTo(target) {
    if (target === 'into.html') {
        window.location.href = 'into.html';
    }
    else if (target === 'index.html') {
        window.location.href = 'index.html';
    }
}

My relevant HTML code:

<a onClick="navTo('into.html')">click</a>
Anna Klein
  • 1,906
  • 4
  • 27
  • 56

1 Answers1

1

This is happening because of your scope when you set onclick it will try to find the function in your global scope, since you defined inside your document ready function it will not run and be set to undefined to solve it you can either declare it as a global function (you already did that), or you can declare an jQuery event...

$(document).ready(function () {
    $('.link').click(function(){
       if ($(this).attr('target') === 'into.html') {
            window.location.href = 'into.html';
        }
        else if ($(this).attr('target') === 'index.html') {
            window.location.href = 'index.html';
        }
    }); 

    window.init = changeColor();

    function changeColor() {
        document.getElementById("url").style.color = "#000000";
    }
});

HTML

<a class="link" target="into.html">click</a>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37