0

There's something going wrong with my java script code. I have a basic html page and this code

<div class="myclass" id="myid"> 
   <h3 class="myotherclass"><?php echo _("Some sentence"); ?></h3>
</div>

When I put this script :

<script type="text/javascript">
    $("div").click(function () {
        alert('hello');
    });
</script>

the click on the div tag triggers the alert message, but when I put this :

<script type="text/javascript">
    $("h3").click(function () {
        alert('hello');
    });
</script>

nothing is triggered. Could some explain this ?

3 Answers 3

1

In fact in this case, you can use jquery's live() syntax : .live( events, handler(eventObject) ), see here here. You can also use on() syntax .on( events [, selector] [, data] , handler(eventObject) ) because live is beginning being deprecated for the recent versions of jquery, see herehere

Sign up to request clarification or add additional context in comments.

Comments

1

You should put your code within document ready handler:

$(document).ready(function(){
   // ...
})

6 Comments

It still doesn't work. By the way, I am noticing that when I use my inspector to hover the zone and when I take the div-tag that contains 'h3' and which is highlighted by the inspector, and when I put this very div tag in the 'click-script', it works just fine. Is it a problem with my browser ?
@user1611830 What do you mean by when I put this very div tag in the 'click-script'? Using class selector? Which browser are you using? Do you see any error on the JS console?
it doesn't work either on chrome nor on safari. In fact the html part of code I put in my question, is in fact wrapped by a div with id "id", and this is this div that is detected by my inspector when hovering the zone. When I replace this div#id in my script, the click triggers the alert message.
@user1611830 Can you provide a demo on jsfiddle.net with your current markup?
indeed it works using jsfiddle but it doesn't work on my browser, though I cleaned the cache...
|
0

did u wrap the code in ready handler.

$("document").ready(function(){})

1 Comment

I think the problem is that the problem is coming from relative positioning : in fact there is a div tag coming after <div class="myclass" id="myid"> <h3 class="myotherclass"><?php echo _("Some sentence"); ?></h3> </div>, say <div id="otherid">...</div> When I use my inspector, the two divs 'myid' and 'myotherid' are hightlighted on upon each other. So how can I circumvent it ?

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.