Javascript : Why can't I use the "this" with childnodes? - javascript

<div id="test" onmouseover="working(this)">
<p>help</p>
<p>me</p>
</div>
<div id="test" onmouseover="not_working(this)">
<p>help</p>
<p>me</p>
</div>
When I use the first function(not_working) it doesn't work, but when I used the second function(working) it does.
function not_working(element){
document.getElementById(element).childNodes[1].innerHTML="succeed";}
function working(element){
document.getElementById("test").childNodes[1].innerHTML="succeed";}
Sorry if I miss something simple, I'm still learning html and only have limited knowledge on javascript.

this is a reference to the element, the event was created from (the div in your case), but getElementById takes an id ("test" in your case).
Also the hovered element is already being passed in the function as element so you can just do:
function working(element) {
element.childNodes[1].innerHTML="succeed"
}

Related

Why can't I retrieve "this" dom element without onclick?

I have a very basic question about using the "this" keyword to retrieve a DOM element.
Consider the following HTML/Javascript:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
console.log(this);
</script>
Here is a div withOUT onclick
</div>
<div class="onclick-div" onclick="console.log(this)">
Here is a div with onclick
</div>
</div>
While clicking the "onclick-div" it does return the DOM object for that div. However, the console.log event calls 'this' indirectly in the "regular-div" and returns window.
Is it possible to get "this" DOM object when 'this' is called indirectly? My purpose is I want to fire a function in line in the HTML, but need to send the function "this". Here's an example of what i'm trying to do:
<div class="container">
<div class="regular-div">
<script type="text/javascript">
loadSomeHTML(this, varA, varB, varC);
</script>
</div>
</div>
Thanks everyone for any clarification of how "this" works in the above context.
In your first example, the script isn't in any way associated with the div. It's just been output within the div, but it's not connected to it. The script runs as the page is being parsed.
Is it possible to get "this" DOM object without a user interaction?
If you mean inline with the parsing of the HTML, you could do this:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Note that the script tag is immediately after the ending </div> tag for the div you're trying to target. The script gets what's currently the last div in the document as of when the script runs. Or of course you could identify the div in some way (a class, for instance) and use that (and then potentially remove it so you could do it again later in the document).
It looks dodgy, but it's perfectly valid cross-browser, and was even recommended at one stage by the Google Closure Library engineers.
Live Example:
<div class="container">
<div class="regular-div">
Here is a div withOUT onclick (look in console for result)
</div>
<script type="text/javascript">
(function() {
var list = document.querySelectorAll('div');
console.log(list[list.length - 1]);
})();
</script>
</div>
Example using a class we move:
<div class="container">
<div class="target-me">
The first div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
<div class="target-me">
The second div
</div>
<script type="text/javascript">
(function() {
var div = document.querySelector(".target-me");
div.classList.remove("target-me");
console.log(div);
})();
</script>
</div>
Note I didn't use id, because if we used an id and JavaScript wasn't enabled, we'd end up with an invalid document (because it would have multiple elements with the same id). It'd be fine if JavaScript were enabled (because we'd remove the id from earlier ones before later ones were created), but...
Javascript has no implicit connection to the HTML DOM. The reason why onclick works the way you want is because the HTML DOM implementation passes the element to the js callback. You need to do something similar in your other case. One way to do this is:
<div class="container">
<div class="regular-div" id="mydiv">
<script type="text/javascript">
loadSomeHTML("#mydiv", varA, varB, varC);
</script>
</div>
</div>
Then your js implementation does the lookup to find the element:
function loadSomeHTML(selector, varA, varB, varC) {
var el = document.querySelector(selector);
// now el is where you want to insert your HTML
// ...
}
The code inside the script tag doesn't have any connection with the tag itself. this should, basically, return the object on which the current function was called, or the global environment, window. In the first div, the code is just executed, on no object, so window is returned. The value of onclick, on the other hand, is treated as a function (with even some parameters, like e), that gets called on the element with the attribute. So, the code in the script element is executed in the global scope, whereas the one in the attribute is in a function scope (that's why all vars are shared across script tags).
As explained in How may I reference the script tag that loaded the currently-executing script?, the proper way of obtaining a reference to the script element whose code is being executed is
document.currentScript;
Then, to get the parent node of that element, use
document.currentScript.parentNode;
<div class="container">
<div id="regular-div">
<script type="text/javascript">
alert('#' + document.currentScript.parentNode.id);
</script>
Here is a div withOUT onclick
</div>
</div>

passing variables on jquery

just having some issues with this jQuery thing.
What i'm trying to do is:
i have some audio control buttons that look like this:
<p>Play audio</p>
but there are too many on the page so i'm trying to optimise the code and make a little function that checks for the div id on the button and adds tells the player what track to play.
so i've done this:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
<script>
$(document).ready(function() {
$("[id^=audioControlButtons-] div.play").click(function() {
var id = new Number;
id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
//alert(id);
player1.loadAudio(id);
return false;
});
});
</script>
my problem is:
the id is not passing to the the player1.loadAudio(id)
if i hardcode player1.loadAudio(1)
it works! but the moment i try to pass the variable to the function it doesn't work...
however if you uncomment the alert(id) thing you will see the id is getting generated...
can someone help?
cheers,
dan
I think I see your problem. The variable id is a string. Try;
player1.loadAudio(parseInt(id));
Yah and the initialise line isn't necessary. Just use;
var id = $(this).parent().attr('id').replace(/audioControlButtons-/, '');
I'm actually kind of confused with your example because you originally have this:
<p>Play audio</p>
but then you don't reference it again. Do you mean that this html:
<div id="audioControlButtons-1">
<div class="speaker"> </div>
<div class="play"> </div>
<div class="pause"> </div>
</div>
Is what you are actually creating? If so, then you can rewrite it like this:
<div class="audio-player">
<div class="speaker"> </div>
<div class="play" data-track="1"> </div>
<div class="pause"> </div>
</div>
Then in your script block:
<script>
$(document).ready(function() {
$(".audio-player > .play").click(function() {
var track = $(this).data('track');
player1.loadAudio(+track);
return false;
});
});
</script>
So a few things are going on here.
I just gave your containing div a class (.audio-player) so that it's much more generic and faster to parse. You don't want to do stuff like [id^=audioControlButtons-] because it is much slower for the javascript to traverse and parse the DOM like that. And if you are going to have multiples of the same element on the page, a class is much more suited for that over IDs.
I added the track number you want to the play button as a data attribute (data-track). Using a data attribute allows you to store arbitrary data on DOM elements you're interested on (ie. .play button here). Then this way, you don't need to this weird DOM traversal with a replace method just to get the track number. This saves on reducing unnecessary JS processing and DOM traversing.
With this in mind now, I use jQuery's .data() method on the current DOM element with "track" as the argument. This will then get the data-track attribute value.
With the new track number, I pass that along into your player1.loadAudio method with a + sign in front. This is a little javascript trick that allows you to convert your value into an actual number if that is what the method requires.
There are at least a couple of other optimizations you can do here - event delegation, not doing everything inside the ready event - but that is beyond the scope of this question. Hell, even my implementation could be a little bit optimized, but again, that would require a little bit more in depth explanation.

How to send a form to a javascript function

I need your help to understand how I can send information from a form to a javascript function.
I've created a basic function here : http://jsfiddle.net/nZhR8/5/
The purpose of this function is to hide/display a div.
In fact, I'll have a table with a few contacts (between 0 and 20). There will be a selectlist per contact. For each contact, I'll have to display 1 special div in function of 1 own particularity. So, for contact1, I may have to display div3, and for contact2, display div1.
I'll also use the javascript function to send to the database wich div has to be displayed. It will be a kind of advancement.
If I'm doing it wrong, please tell me why.
I don't see the idea behind this but that could do the trick: http://jsfiddle.net/YCPM7/
That must be a simple draft of a much bigger project.
Also, I would suggest that you either use a common class for each DIVs
<div class="message 1">1</div>
<div class="message 2">1</div>
<div class="message 3">1</div>
...
So you can simply do:
$(".message").hide();
Enjoy.
Firstly, remove the $(...) from where you define the function showDiv, as you don't want to execute showDiv when the page has loaded.
Apart from that, your problem seems to be jsFiddle. It didn't work there, but when I copy+pasted exactly what you posted on jsFiddle into a file, fixed what I mentioned above and tried it in FF, it worked.
There are of course things you can do better about your code, but it works. Suggestions: Give all divs the same class and distinguish them by id, then hide everything with that class and show the one with the correct ID. For the onload, instead of copying the whole code just execute showDiv(1).
You need something like this jsFiddle?
<div id="1" class="1">1</div>
<div id="2" class="2">2</div>
<div id="3" class="3">3</div>
<div id="4" class="4">4</div>
<div id="5" class="5">5</div>
$('div').hide();
$('#StateSelection').change(function() {
var $this = $(this);
$('div').filter('.'+$this.val()).show();
});

Easiest way to get element parent

Suppose i have this structure of elements:
<div class="parent">
<div class="something1">
<div class="something2">
<div class="something3">
<div class="something4"></div>
</div>
</div>
</div>
</div>
And code like this:
$(".something4").click(function(){
//i could do it like this...
$(this).parent().parent().parent().parent().parent();
});
But that seems to be stupid, is there a better way to do this?
also i can't just say $(.parent) because there are many divs like this with class parent in my page.
Use .closest(selector). This gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
$('.something4').click(function() {
$(this).closest('.parent');
});
Use .closest():
$('.something4').click(function() {
$(this).closest('.parent');
});
I think you should try this
$(this).parents(".parent");
But I don't know where on the page are the other divs with this class :)
You could always use .parentNode (standard JavaScript). It's generally a bad idea to use class names that coincide with function/variable names from the library you're using (this goes for any language). Making your class names more unique is a better approach (for instance, "scparent" instead of "parent", if the name of your application was "Super Calculator" or something). This avoids conflicts such as the one you're describing.
I would caution using .closest(), simply because you may create a function like this:
function getParentElem() {
return $(this).closest('div');
}
And it would grab the parent div's in your code just fine, but if down the road you add a table for displaying data, and you run the function through a child element of the table, you will have to create another implementation that selects the table element, because that's what you now want:
<div id="tableParent">
<table id="dataTable">
<tr id="target1">
<td>Some data.</td>
</tr>
</table>
</div>
By using your function getParentElem() on the tr element, you'll end up grabbing the div with id="tableParent", rather than the actual parent, which is the table element. So, unless you've delineated your parent classes appropriately all the way through your code (which can be a pain and isn't always efficient), you may run into problems. Especially if at any point you're creating elements programmatically, or reading in data from another 3rd-party library or script.
Not saying it's not good to use .closest()... just pointing out a possible "gotcha".
i would suggest adding to the div parent an id like 'parent_1' etc. and in every son you keep the id in the rel attr
<div id="parent_1" class="parent">
<div rel="1" class="something1">
<div rel="1" class="something2">
<div rel="1" class="something3">
<div rel="1" class="something4"></div>
</div>
</div>
</div>
</div>
$(".something4").click(function(){
//i could do it like this...
$('#parent_' + $(this).attr('rel'));
});

Is there a simple Javascript command that targets another object?

I have a page with two divs in it, one inside the other like so:
<div id='one'>
<div id='two'></div>
</div>
I want div one to change class when it is clicked on, then change back when div two is selected.
I'm completely new to javascript, but I've managed to find a simple command that makes div one change when I click it.
<div id='one' class='a' onclick="this.className='b';">
<div id='two'></div>
</div>
Now I just need an equally simple way to change div one back when number two is clicked.
I've tried changing "this.className" to "one.classname," and for some reason that worked when I was working with images, but it doesn't work at all with divs
<div id='one' class='a' onclick="this.className='b';">
<div id='two' onclick="one.className='a';">
This does not work.
</div>
</div>
Essentially I'm wondering if there is a substitute for the javascript "this" that I can use to target other elements.
I've found several scripts that will perform the action I'm looking for, but I don't want to have to use a huge, long, complicated script if there is another simple one like the first I found.
You can use document.getElementById
<div id='two' onclick="document.getElementById('one').className='a'; return false;">
This does not work.
</div>
This would work:
document.getElementById('one').className = 'a';
you could get the element by id with:
document.getElementById("one")

Categories

Resources