Search code examples
javascriptunobtrusive-javascript

How do I make my click catcher work?


I'm trying to create a simple click catcher where if you click .image-class the javascript will take the href from another element with a class name of .btn and send you to it's destination. Though I keep getting errors on lines 7 & 10 saying that undefined is not a function. How do I make this work?

<script>
var ClickCatcher=
{
    init:function(){
        var link = jQuery('.btn')[1].href;
        var imgCatch = jQuery('.image-class');
        imgCatch.addEventListener("click", ClickCatcher.clickListener, false);
    },
    clickListener:function(){
        window.location = link;
    }
};
ClickCatcher.init();
</script>

Solution

  • You can do this with jquery with a simple click event

    jQuery('.image-class').on('click', function (){
        window.location = jQuery('.btn').eq(1).attr('href');
    });
    

    But if you still want to write in the way you have you can do:

    var ClickCatcher = {
        init: function () {
            jQuery('.image-class').on('click', function (){
                window.location = jQuery('.btn').eq(1).attr('href');
            });
        }
    };
    
    ClickCatcher.init();
    

    Just make sure to fire the init method after dom load.

    update: One issue with it is that you have coded your target etc in the code rather then pass it, so its going to be hard to reuse, you'd be better off doing:

    var ClickCatcher = {
        init: function ($button, loc) {
            $button.on('click', function (){
                window.location = loc;
            });
        }
    };
    
    ClickCatcher.init(jQuery('.image-class'), jQuery('.btn').eq(1).attr('href'));
    

    That way the internal working is seperate from the dom (as you are passing the dom dependencies to the function.