I am running through a few jQuery tutorials but I can not seem to find the awnser to this confusion.
<div id="container">
<a href="#">Click Me</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>
function doSomthing(){
aMessage = message;
console.log(this);
console.log(aMessage);
}
$('a').on('click', doSomthing)
</script>
Looking at the code above as a user clicks the anchor tag and the doSomthing function runs.
However what i dont understand is why, if the code is changed to the following (adding the parenthesis to doSomthing), the doSomthing function runs immediately without clicking the anchor tag.
$('a').on('click', doSomthing())
Further from this what happens if I would like to pass a parameter when running doSomthing on click. For Example
<div id="container">
<a href="#">Click Me</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script>
function doSomthing(message){
console.log(this);
console.log(message);
}
$('a').on('click', doSomthing('face bash'))
</script>
What I would normal expect is that after I have clicked the anchor tag the console would log 'this' and the passed string, however the doSomthing function is run as soon as the page loads and not when the anchor tag is clicked :S
How would you normal pass parameters to functions called through other functions :S?