level 2 DOM handling not working javascript - javascript

hello I'm having trouble using level 2 DOM to handle events, i've looked around but just don't quite understand how it works, and allways end up doing simple code like:
<element onClick = " some code" > </element>
instead of reaching the element from outside of html code, please help, I know this is an easy topic but just can't make it work...
there is also some css code but its not relevant to my question so here's my code:
<script type="text/javascript">
function rotate( xy , deegrees){
document.getElementById("cube").style.WebkitTransform = " rotate"+xy+"("+deegrees+"deg)";
}
// so this is where its supposed to be but not working
// whats wrong ?
document.getElementById("upp").addEventListener("click", rotate('X', 540), true);
myFunction();
</script>
</head>
<body>
document.getElementById('cube').style.WebkitTransform = 'rotateX(90deg)';
<div id="button_container">
<button id="upp" onMouseOver=" rotate('X',90); "> UP</button>
<button id="downn" onMouseOver = " rotate('X',-90); "> DOWN</button>
<button id="leftt" onMouseOver = " rotate('Y',00); "> LEFT</button>
<button id="rightt" onMouseOver = " rotate('Y',-90); "> RIGHT</button>
</div>
<section class="container">
<div id="cube">
<figure class="front">front</figure>
<figure class="back">back</figure>
<figure class="right">right</figure>
<figure class="left">left</figure>
<figure class="top">top</figure>
<figure class="bottom">bottom</figure>
</div>
</section>

This is a function call:
rotate('X', 540)
It's a function call no matter where it appears, like when you call addEventListener:
document.getElementById("upp").addEventListener("click", rotate('X', 540), true);
Thus, you're passing the result of calling your "rotate" function instead of the function itself:
document.getElementById("upp").addEventListener("click", function() { rotate('X', 540) }, true);
By wrapping the function call in another function, you correctly supply addEventListener() with an event handler to be called when the "click" happens.
In addition to that, you're trying to add the event handler in a script block that appears before the DOM element you're trying to affect. When the script runs, there won't be an element in the DOM with the id you're looking for. Either wrap your event handler setup in a "load" event handler, or move the script block to the end of the <body>.

Your code likely is running before your DOM is applied. Move script tag to bottom of page or use onload function to execute your code after the DOM has completed its load phase.
http://api.jquery.com/ready/
Validate this by ensuring you can log a element you are attempting to get a reference to...
console.log(document.getElementById("upp"));
Should return a DOM element.

Related

Calling a function when anything in the HTML body changes without using onclick or setInterval

I have a HTML code as :
<body>
<div id = "mypage">
<svg>....</svg>
<div>Hello all, how are you?</div>
<img>........</img>
</div>
</body>
When I highlight any part on this page (highlighting "how are") a span is attached to this part in the body and the resulting code becomes:
<body>
<div id = "mypage">
<svg>....</svg>
<div>Hello all, <span class="highlight">how are</span> you?</div>
<img>........</img>
</div>
</body>
This means a change has occured in the HTML body. Now, when this happens I want to trigger a javascript function. i.e. the function should be called whenever any change in the body happens.
I know this can be done by running the function via setInterval and continuously checking for any changes. Can I avoid it and trigger the function just when any change occurs?
did you try this in your JS(Jquery is required).
$(body).change(function() {
yourFunction();
});

Can't make jQuery callbacks to work properly while calling same function repeatedly

I have a simple share button aside every post, I'm using .toggle() function to show and hide the options. The code looks something like this:
<div id="posts">
<div class="post">
<div class="content">
Post content
</div>
<div class="share">
<div class="trigger"> Share </div>
<div class="hidden"> Share on Facebook </div>
<div class="hidden"> Share on Twitter </div>
</div>
</div><!-- each post -->
<div id="new">
</div><!-- new post container -->
</div><!-- Posts -->
<script>
function shareThis(){
$('.trigger').click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis();
});
});
</script>
I call this function once when the page loads, and then every time a new post is loaded.
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded. I also tried this with 'each' function but same result.
So it's just working for the last call, similar to these question i found here and here, and some others, but didn't get a solution for my problem there.
Thanks!
The problem is, it works in the first time when the page is loaded, and just works for the new element when a new post is loaded.
Your issue could be that you are binding the event twice (or as many number of times you load #new contents) to the existing .trigger by calling shareThis inside the load callback. So basically when you click on the old .trigger it will trigger the handler twice, i.e toggling it twice which keeps them in the same state. SO either bind the event to the newly added ones alone or turn the click event off and turn it on in the function shareThis:
function shareThis(){
$('.trigger').off('click').on('click', function(){
$(this).siblings().toggle();
});
}
You could also try:
function shareThis(ctx){
ctx = ctx || document;
$('.trigger', ctx).click(function(){
$(this).siblings().toggle();
});
}
$(document).ready(function(){
shareThis();
$('#new').load("/post2", function(){
shareThis(this);
});
});
Try binding the click to the document instead. Only need to do it once :)
$(document).on('click', '.trigger', function () {
$(this).siblings().toggle();
}).ready(function () {
$('#new').load("/post2");
});
http://api.jquery.com/on/
http://training.bocoup.com/screencasts/more-efficient-event-handlers/

jQuery on method with ajax response [duplicate]

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
I have a <select class="listenToMe" /> that when changes does something. I also have a separate link that when clicked performs an ajax request and returns more dom elements and inside them it has another <select class="listenToMe" />
I would like my event listener to be applied to this element as well. I am trying to use jQuery's on method but it doesn't appear to be working:
JS
var selectListener = function() { alert('you change me!'};
$('.listenToMe').on("change", selectListener);
$('.addMore').click( function() {
$.post('myWebPage.php', {} , (function(data) {
$(this).before(data);
// data is something like <div><select class="listenToMe" /></div>
}).bind(this));
});
HTML
<div>
<div>
<select class="listenToMe" />
</div>
<div>
<select class="listenToMe" />
</div>
<a class="addMore">Click me</a>
</div>
Any suggestions?
You can try
$(document).on('change', '.listenToMe', function(){
// Your code here
})
Your using on like live. The difference is subtle but important. You attach on to a static element in your markup and then filter the event based on a selector. This way the on event never goes out of scope, e.g. if I have the markup
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
</div>
which when I add my dynamic markup will become:
<!-- this div is not dynamically loaded-->
<div id="mystaticDiv">
<!--insert dynamic content here-->
<div class="myDynamicdiv></div>
</div>
To fire an event on the click of my dynamic div that never needs rebinding I would write the following jQuery:
$('#mystaticDiv').on('click', '.myDynamicdiv', function() {/*Do stuff*/});
So I'm binding my on to the #mystaticDiv but filtering on .myDynamicdiv. Now I can add as many .myDynamicdivs as I want and this will work.
I mentioned live. This is deprecated but works in the same way as you were attempting. This attaches an event to the document of the page with a selector base on the selector your attaching live to. So $('.myDynamicdiv').live('click', function() {/*Do stuff*/}); is directly equivalent to $(document).on('click', '.myDynamicdiv', function() {/*Do stuff*/});. the reason I mention this is this is how you were trying to use on.
Your code $('.listenToMe').on("change", selectListener);. Will not work for dynamic content. This code attaches the event to the dynamic content, that doesn't exist yet. So the is never actually bound. Interestingly $('.listenToMe').on("change", selectListener); is exactly what $('.listenToMe').change(selectListener); does under the hood.

Finding the source of a click in event bubbling

I have the following code:
<div id="buttons">
<button id="btn1">1</button>
<button id="btn2">2</button>
</div>
I attach an event handler to the <div> to handle clicks.
When I click a button, the event is captured by the div. Is there a way to get the source of the event?
For example, if the event were on each of the the buttons then the this keyword would refer to the buttons. When it's on the <div> it refers to that.
When the click is caught by the div, is there a way to locate the source of the click? i.e. which actual button was clicked?
Thanks all
Dave
You can use the originalTarget property of the event object to find out the source of the event.
JSFiddle
HTML
<div id="buttons">
<button id="btn1">1</button>
<button id="btn2">2</button>
</div>
JavaScript
document.getElementById('buttons').onclick = function (evt) {
var source = evt.srcElement || evt.originalTarget
alert(source.id);
}
If you use jQuery, this should help:
$("#buttons").click(function(evt){
alert($(evt.target).attr("id"));
});

Execute Jquery on div in ajax loaded contents

I have a page called forms.php with a javascript included in its head and a div called fadeinContents
i used Ajax to load part of a file called #sections1 into this div which works quite well
But i need to execute some Jquery on the loaded contents in the fadeinContents when they are clicked. Ive read other post but couldn't understand them well..
Here are my files
forms.php
<html>
<head>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/login.js"></script>
</head>
<body>
<div class="login_link">login</div>
<div class="signup_link">signup</div>
<div class="fadeinContents">
<!--Loaded contents goes here -->
</div>
</html>
Here's my Jquery
$(document).ready(function(e) {
$('#fadeinContents').load('forms.php #sections1');
$('.login_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections1');
});
$('.signup_link').click(function(e) {
$('#fadeinContents').load('forms.php #sections2');
});
$('.recoverPassword').click(function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
});
Loaded File containing
<div class="sections1">
<div class="signup">
<!-- Signup Forms Here -->
</div>
</div>
<div class="sections2">
<div class="login">
<!-- loginForms Here -->
</div>
</div>
<div class="sections3">
<div class="recoverPassword">
<!-- recover form Here -->
</div>
</div>
My problem is that the Recover password click function is not working because it was loaded, Please how can i make this work?
thnx in advance..
then you should bind that event differently. try it like this
$('.fadeinContents').delegate('.login_link', 'click', function(e) {
$('#fadeinContents').load('forms.php #sections3');
});
and so on for the rest of them.
This means that the click event is binded on the .fadeinContents but when triggered, it checks if the target is a .login_link and if so it will triggers the given callback. So delegating the event handler to a higher node will ensure that no matter when the content of the node will load/change or how many elements you have, if they match the criteria the event handler will trigger.
Delegating events is a bit more memory efficient as well. If you have for example one hundred cells you want to add click events to, doing a $(".cell").click( will attach a event listener on every one of them. Delegating it to the body for example with $("body").delegate('.cell', 'click', will only attach one event (and then do some looping and checking there, that's true) but you'll end up with only one event listener and it won't matter how many nodes you later add or remove. they will trigger that click event

Categories