getElementById() not working - javascript

The following code is somewhere between my head tags:
<script type="text/javascript" src="js/jquery-2.0.3.js"></script>
<script type="text/javascript" src="js/homepage.js"></script>
Somewhere in the body:
<input type="text" id="registreervoornaam" name="registreervoornaam" placeholder="Voornaam">
In my homepage.js:
window.onload=function(){
var regname = document.getElementById("registreervoornaam");
regname.focus = function() {
alert("bla");
};
};
Somehow I do not get an alert when focussing on the input field. Any idea's on what this might be? I added the function in the onload because otherwise regname will become null as the javascript file is parsed before the body.

What i would do to solve this:
See if the value returned by getElementById is null. If it is, it means that your element doesn't exist in the page. If that is the case, you may want to put all of your scripts at the end of the markup file, so that when the scripts are loaded, the whole DOM has already been loaded.
If you are already importing jQuery, why not use it? :D I would just do:
$("#registreervoornaam").focus(function() {
//do stuff here that you want to be triggered on focus
});
i just realised that there is no "focus" in plain js :/ I would use onfocus instead. Here are more details about it >> here
Good luck! :D

If you're going to set up the event handler that way, the property name is "onfocus", not "focus".
regname.onfocus = function() {
alert("bla");
};

And if you have jQuery on your page you could write :
$(function(){
$("#registreervoornaam").onfocus= function() {
alert("bla");
};
});

Related

How do I remove a script tag by its content and its src?

I need to remove a script tag (<script>...</script>) by its content and/or its src property. Taking as example this:
<script type="text/javascript">
var adfly_id = 2776246;
</script>
<script src="https://cdn.adf.ly/js/display.js"></script>
I've tried this code:
jQuery(document).ready(function($){
$('script').each(function() {
if (this.src === 'https://cdn.adf.ly/js/display.js') {
$(this).remove();
}
});
});
But without success (I am using that code from within WP - if anyone is asking why that jQuery syntax), can any give me some advice?
EDIT: The idea here is remove the script to prevent its execution
This seems to work:
jQuery(document).ready(function($){
$('script').each(function() {
if (this.src === 'URL_HERE') {
this.parentNode.removeChild( this );
}
});
});
You can't remove the script tag I believe but I believe you can remove the src attribute in the script tag which render it useless if you removed $(this).attr('src');
Try
$(document).ready(function(){
$('script').each(function() {
var obj = $(this);
if (obj.attr("src") == 'https://cdn.adf.ly/js/display.js') {
obj.attr("src","");
}
});
});
You can hack it. Use another script to do a....
node.parentNode.replaceChild(
document.createComment(node.outerHTML.slice(1,-1)
.replace(/--/g, '\\-\\-')), node);
Where node is your script node/element. The replacing of double dashes is to prevent the browser complaining about an uncompliant comment tag.
Then if you want to enable it just do the reverse comment.replace and enclose with < and >. But you probably need to keep track of the modified script node, because after it becomes a comment it is less query-able.
Just remember that the script is loaded early on, so your removal code should come before the node you want to remove. I had success using and mutation observer that I start in the header that watched for added script nodes and disabled them immediately. Then I analyzed the script node code (both as content and by
XMLHttpRequest
-ing the src if it exists. Then once I had my way with it I would re-enable it by doing the reverse disable operation by creating a code fragment and injecting the original outerHTML, either modified or not.

How to listen to a script tag's onload event?

<script id="me" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script
<script>
var oB = document.getElementsById('me');
me.onload = function(){
alert('OK');
}
</script>
Why me.onload is not triggered after the script is loaded?
There are 2 issues:
a missing > at the end of the first line (you have written </script instead of </script>)
there is no variable me: you have retrieved the script tag into a variable oB.
Thus, you can fix your code by change me.onload = ... to ob.onload = ....
Moreoever, you should avoid using inlined declaration of event listeners such as <script onload="...">.
Last but not least, you should use addEventListener instead of onxxx: addEventListener vs onclick
document.getElementById instead of document.getElementsById
oB instead of me
<script id="me" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script
<script>
var oB=document.getElementById('me');
oB.onload=function(){
alert('OK')
}
</script>
But this won't work either because me is already loaded like the other answer states.
before you execute the alert codes, the script tag with id "me" is already downloaded, so despite the syntax error in your code, you can not get the alert.
you can simply use:
<script id="me" onload="alert('OK');"src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

Javascript window.onLoad element content not changing

Im having a problem with changing an elements content
HTML Code:
<script type="text/javascript">
// Javascript
function promptLogin()
{
var person=prompt("Please enter your name","User");
if (person!=null)
{
x="Hello " + person + ", welcome to JBA Limited";
document.getElementById("topBar_message").innerHTML=x;
}
}
</script>
</head>
<body>
<script>window.onLoad = promptLogin()</script>
<header>
<div class="bul_header_topBar">
<p id="topBar_message">Welcome to JBA Limited</p>
</div>
I am unsure of the problem but I fear the problem is with the function being called before the webpage is loaded and therefore no id is present. Either that or have spelt/defined something wrong.
Bull
You need to strip the () from promptLogin
edit: oh yeah, and it's onload, not onLoad
bigger edit:
window.onload waits until your DOM is loaded, so there's no way it's not there. This is just a case where you are trying to pass a method that has already been run. The () at the end of promptLogin means "window.onLoad is equal to the return value of this function", not what you are looking for ("window.onLoad equals this function").
Also, once upon a time browsers were less case-sensitive when it came to these callbacks, but now they are. it's window.onload.
My guess is that your dom is not loaded yet, so when you try to "get" your element its not loaded/there yet.
You can either add what I suggest below, or leave everything as it is, except remove the onload etc.. and put that call (with the script tag) at the very bottom of your page.
//at the bottom of your page within script tags
<script>promptLogin()</script>
Put this code at the bottom (under) your dom.
add the code below to your page, at bottom within script tags.
remove this window.onLoad = promptLogin()
(function()
{
var person=prompt("Please enter your name","User");
if (person!=null)
{
x="Hello " + person + ", welcome to JBA Limited";
document.getElementById("topBar_message").innerHTML=x;
}
})()
What el_bob says is correct, however rather than just stripping () I would use the anonymous function syntax because it is more common thus more readable:
window.onload = function(){
promptLogin();
}
The main advantage of this syntax is that you can make multiple calls:
window.onload = function(){
promptLogin();
anotherFunction();
thirdFunction();
}

Run JavaScript function on element defined with jQuery

Not sure I titled this well.. show's that I'm in unfamiliar territory. How can I run a JavaScript function based off of the element called in a jQuery function?
Theory:
<script type="text/javascript">
$.fillit('video');
</script>
(run fillit on video tag present in page.. interchangable with other elements)
$.fillit = function(){
this is where it says "run on the tag defined in the jQuery function"
}):
$.fn.extend({
fillit : function(){...}
});
then...
$('.video').fillit();
Edit (after comments)
To fill a dom element with other elements/html:
var img = document.createElement('img');
img.setAttribute('src', 'somesrc.jpg');
$('.video').append(img);
or
$('.video').html('<img src="somesrc.jpg"/>');
You can do it the way you described like so
<script type="text/javascript" language="javascript">
$.fillit = function(content)
{
$("result").html(content);
}
//call function
$.fillit("HELLO WORLD");
</script>
or as Alexander just posted if you want to do it on the selected element.
I don't think adding functions directly to jquery with $.func = is a good idea though. If jQuery ever adds a fillit method your method will conflict with theirs.
technopeasant, it sounds like you are using a jquery plugin (in your example, a plugin called 'fillit') and it is asking you to run the plugin on a tag or series of tags. Sorry if I misunderstood your question.
If that is the case, all you need to do is one of two things. If you are trying to run it on a very specific element in the HTML page (one with an id like <div id="myvideo"></div>) then all you need to do is run:
$('#myvideo').fillit();
//Notice the '#' symbol, that looks up the element with an id of 'myvideo'
If you want to run the plugin on a series of elements (like all <p> tags in the entire document, you'd run something like:
$('p').fillit()
//notice no '#', it's just looking up all <p> tags regardless of ID.
Take a look at the jQuery documentation regarding selectors to get a more concrete idea of how these selectors work:
http://docs.jquery.com/How_jQuery_Works
Someone answered with a link to this: http://docs.jquery.com/Plugins/Authoring
exactly what I was looking for. claim your kudos!
(function( $ ){
$.fn.fillit = function() {
this.fadeIn('normal', function(){
var container = $("<div />").attr("id", "filled")
.appendTo(container);
});
};
})( jQuery );

Categories