Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery onclick by class name - how to

i have: <a class='category' href='view.php?category=1'>category</a>

i do: $("a.category").click(function(){alert("dsafdfad")})

and nothing happens??

start("view.php?"); posts("view.php?");

function start(link){
    $("#country ul").load(link+"mode=start",function(){
    $("#country a").click(function(){
        var link=encodeURI($(this).attr("href"));
        category(link+"&");
        posts(link+"&");
        return false;
        });
    });
}

function start2(link){
    $("#country ul").load(link+"mode=start",function(){
    $("#country a").click(function(){
        var link=encodeURI($(this).attr("href"));
        posts(link+"&");
        return false;
        });
    });
}

function posts(link){
    $("#posts").load(link+"mode=posts",function(){
    $("a.country").click(function(){
        var link=encodeURI($(this).attr("href"));
        category(link+"&");
        posts(link+"&");
        return false;
        });
    $("a.category").click(function(){
        $("#category").css("display","none");
        var link=encodeURI($(this).attr("href"));
        start2(link+"&");
        posts(link+"&");
        return false;
    });
    });
}

function category(link){
    $("#category ul").load(link+"mode=verNav",function(){
        $("#category").css("display","block");
        $("#category a").click(function(){
        var link=encodeURI($(this).attr("href"));
        posts(link+"&");
        return false;
        });
    });
}
like image 897
daniel.tosaba Avatar asked Dec 08 '25 22:12

daniel.tosaba


2 Answers

You need to ensure that the jQuery line is called when the element is already been created and present in the HTML DOM. In other words, do it during $(document).ready() in page head

<head>
    ...
    <script>
        $(document).ready(function() {
            // Here.
        });
    </script>
</head>  

or put the script at bottom of the page body, after the elements of interest.

<body>
    ...
    <script>
        // Here.
    </script>
</body>
like image 179
BalusC Avatar answered Dec 11 '25 12:12

BalusC


Works for me. A few things to check:

  • Are you clicking the link?
  • Are you waiting until the DOM loads before binding to the click event?
  • Is jQuery loaded?
like image 25
David Avatar answered Dec 11 '25 11:12

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!