Can I just put my javascript right next to my <div> - javascript

If I have some javascript/jQuery acting on a particular div inside tags (for an animation), can I just put the javascript (in a src="link-to-my-js.js" file) right next to my div?
I mean something like the following:
<body>
<div id="special">Some html</div>
<script type="text/javascript">javascript related to my div tag above...</script>
</body>

whereever you add your code wrap it with document .ready.
It will wait till all the dom is ready, so you will be safe.
<script type="text/javascript">
$(document).ready(function() {
});
</script>

You can put them anywhere you want, but
For performance reasons, it's best to put them at the bottom of the page.
DOM manipulation before the page has loaded can cause problems, especially with IE, for example this google maps problem.

You can add the tag anywhere you please. Remember though that if your script tries to act on an element that has not yet been loaded it will fail.
So if your load your script tag before your div and the script isn't activated by an onload event or something similar element will not be found.
On the contrary if the tag appears after the element you can manipulate it as normal.

It does not matter where you put it if you wrap your code with the $(function(){/*code here*/})
reference: http://api.jquery.com/jquery/#jQuery3

Related

Focus ContentEditable div

I want to focus the contenteditable div, so that I can automatically start typing when it is inserted into the DOM
I have tried $('.content').focus(), but this does not work
Example html:
<div class="content" contenteditable="true">sample input</div>
I think you probably just need to wrap your code in a window.load function:
$(window).on("load",function(){
$('.content').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content" contenteditable="true">sample input</div>
(fiddle: http://jsfiddle.net/hxeqm541/)
What this does is, it waits until the page is fully loaded, before it executes the code inside the window.load.
If you don't do this, the code to focus on the div will be executed before the div even exists on the page, which is impossible. By the time the div finally does exist on the page, the code has already run, so nothing will happen anymore.
Side notes:
Because you reference the div by its class ($('.content')), if you have more than one of these divs with the same class-name, only the last one will receive focus. See example.
You DO NOT NEED to wrap every individual code block in an window.load.
Usually, you can wrap your ENTIRE JavaScript code in the window.load. There might be a few exceptions to that rule, read this and this to fully understand the workings of the window.load mechanism so you'll know exactly how to use it.
(Notice in the second link that .load can also be used on other elements.)

Safe AND quickest way to add a css class to the body of the DOM

I am looking to add a class to the body element of the DOM. For something so simple, and with the body element itself loading quick (at least, I would think it would load quicker than, say, an element buried deem in the DOM), must I really wait for the jQuery Ready event to do such a simple task? I'm looking to avoid a "flicker" effect when adding the style to the body, since I'll have different CSS styles attached to this class take effect when added.
I can do something like:
jQuery(window.document).ready(function () {
jQuery("body").addClass("home");
});
But is there a faster, yet safe way? I don't care if its jQuery or native JavaScript
document.body.className += ' home';
Performance comparision: className vs classList vs addClass :
Update(based on PSL's comment)
or for newer ones document.body.classList.add("home");
Make sure you do this under the <body>, it won't work if applied from a <head> script
Right after the opening body tag, you can create a script tag :
<body>
<script>
$('body').addClass('home')
</script>
<!-- HTML content bellow -->
</body>
The only condition is that the jQuery is loaded in the head.

Targeting an ID that is rendered by a script

I'm using a nifty little script called Tabifier (http://www.barelyfitz.com/projects/tabber/)
Now, long story short, this script, which I run in my head tag, creates a <ul> with <li>s containing <a>s. Also in the head tag it creates IDs for these <a>s. When I inspect the loaded site I can clearly see the ID tags present. However, I cannot call them using getElementById. I've been using
<script>
document.getElementById('rightpanelnav1').style.padding='200px';
</script>
as a sample script in different parts of my code but to no avail. I'm wondering wether it's the placement or order in which these things are defined in my code that's causing it not to recognize the ID. What do you think?
EDIT: I recieved a great answer below, but I still can't get 'rightpanelnav1' to register onclick events...? It's an , there shouldn't be a problem, right? And when I click it, the entire page has been loaded for several seconds...
Firstly, in order to access an element in the DOM, the element must be a part of the DOM (document). So if you place your <script> with getElementById in the page at a place prior to where the element is loaded, it will not see the element in the DOM.
Secondly, it is highly probable that this library you use does its modification on page load, which would mean that no matter where you place your <script> it would have no chance of seeing these elements before running.
As a result, you should have your script wait as well, and do this:
window.onload = function(){
document.getElementById('rightpanelnav1').style.padding='200px';
};
Or for a click event
window.onload = function(){
document.getElementById('rightpanelnav1').onclick = function(){
alert("clicked!");
};
};

How can Javascript in the head access elements in the body?

I often see some JavaScript libraries that are called in the head tag of an html page. However, if these libs call an element in the body tag, there'll be a response (still from the head tag). When I try to call an element from the head, there is no response - why?
Thanks in advance. :)
The browser parses the html page from top to bottom, executing any <script> blocks in place as it finds them. Which means if the JavaScript attempts to access elements on the page it can only see those included higher in the page because the ones lower down have not been parsed yet.
There are two ways to deal with this:
Put your <script> block at the bottom, just before the closing </body> tag (or at least put it after the elements it needs to reference), and/or
Use an onload (or, if you like jQuery, a $(document).ready()) handler.
One way to setup an onload handler is like this:
<head>
<script>
window.onload = function() {
// this function will be called by the browser after
// the entire page has loaded and thus code in the function
// can access any element on the page.
};
</script>
</head>
<body>
... various elements ...
</body>
You may have also seen something like this:
<body onload="someFunction();">
Where someFunction() can be defined in a <script> block in the <head>. It's basically the same thing, but it's so 1990s to do it with an attribute in the html like that. (Actually even the window.onload() is out of date now, but it works and I don't have time to explain the .addEventListener() method.)
That's beacause you propably are trying to call elements before they exist, ie. the HTML isn't parsed yet. To avoid this, you have to wait untill the page is completed, and then execute your script.
To achieve this, you have to assign your function into a onload-event. For example:
<body onload="your_func">

How to insert an element at the current position in HTML using prototype

How do you insert an HTML element dynamically (using prototype) at the current position if you don't know the id of the parent element? All examples I've seen assumes the element has some kind of id.
I.e.
<script>
function addSomeHtmlAtCurrentPosition()
{
current_element = ...; // Magic?
current_element.insert(...);
}
</script>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- should insert something here... -->
</div>
<div>
<script>
addSomeHtmlAtCurrentPosition();
</script>
<!-- ... and then here -->
</div>
I've tried using prototype with $$('div').last(), but that doesn't seem to work (last() sometimes reports back another div if I use libraries such as livepipe).
What I really want is something similar to document.write, but using prototype instead of raw html.
The only way I can think of is finding the <script> element and insert the element before/after the script. The thing is, all DOM methods need a DOM node to operate on. Executing scripts that modify the DOM before the document has loaded isn't a good and safe idea.
Similar questions linked below.
JavaScript: get the current executing <script> node?
How may I reference the script tag that loaded the currently-executing script?

Categories

Resources