Javascript – Use JavaScript-Variable in jQuery

javascriptjqueryvariables

I´m having a normal JavaScript-function and want to use the Variable (myVar) also in my jQuery Code – is this possible? and how?:

<a onclick="showtitle(abctitle);" href="#">Testlink</a>

<script>
function showtitle(myVar) {
    myTitle = myVar;    
}

$(document).ready(function() {
    alert(myTitle); //I would like to alert "abctitle"
};
</script>

Best Answer

Firstly, don't mix DOM0 inline event handlers with jQuery. Separate your markup and your logic.

If you use a data- attribute you can put your variable's content in your HTML, and then extract that in the event handler:

<a id="test" data-foo="mytitle" href="#">Testlink</a>

and then:

$(document).ready(function() {
    $('#test').on('click', function() {
        alert($(this).data('foo'));
    }
});

In this code the alert won't appear until the link is actually clicked on, of course.