Question

<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>
<a href="#" class="audiocontrol"></a>

<script>
    function playController(dataObj){
        alert(dataObj);
    }

    function playHandlers(){
        var dataObj = "stef";
        $('.audiocontrol').on('click', playController(dataObj));
    }

    $(document).ready(playHandlers);
</script>

This bit of code is firing off on page load whether I click the object or not. Why?

Was it helpful?

Solution

What you want is:

function playController(dataObj){
    alert(dataObj);
}

function playHandlers(){
    var dataObj = "stef";
    $('.audiocontrol').on('click', function() { playController(dataObj); } );
}

$(document).ready(playHandlers);

The way your code was written, it was calling playController when you were registering it in the .on call.

jsfiddle

OTHER TIPS

You're invoking the function therefore passing the result of playController. You can do something like this.

function playHandlers(){
    var dataObj = "stef";

    $('.audiocontrol').on('click', function() {
        playController(dataObj);
    });
}

This will work:
(demo here)

function playController(dataObj) {
    alert(dataObj);
}

function playHandlers() {
    var dataObj = "stef";
    $('.audiocontrol').on('click', function () {
    playController(dataObj)
   });
}
$(document).ready(playHandlers);

This will load your code when the page loaded and call the function playHandlers(). You were calling it directly because you forgot to add function(){} in the on/click call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top