0

I have this very simple jquery script:

$(document).ready(function() {

    $("h2").click(function(){
        alert("Hello world");
    })    
});

When I click on any h2 on the entire site, an alert will show up.

This works fine when I put an h2 anywhere in my index.html but when I put the h2 in some of the files included by angular, nothing happens when I click on the h2.

These are my files

index.htm
included.htm
myjqueryfunctions.js

Here is how I include the jquery-file

<body>
.... some code ....
<script src="jquery_functions.js"></script>
</body>

Here is how I include the HTML-file using angular

<div ng-include src=" 'included.htm' "></div>

Everything else is working fine.

Question: Why does my jquery-script work fine when I put the h2 in my index.html but not when it is in the included.html

1 Answer 1

1

Hi you should call selector as below

 // This WILL work because we are listening on the 'document', 
    // for a click on an element with an tag h2
    $(document).on('click',"h2", function(){
            alert("Hello world");
        })  

    // This will NOT work because there is no 'h2' (added later or injected by angular)... yet
    $("h2").on("click",function() {
        alert("hello");
    });
Sign up to request clarification or add additional context in comments.

1 Comment

CodeIsLife: Your answer did my day. It works perfect now! I salute you!! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.