How do i use javascript to manipulate empty divs? - javascript

So this is what i want to do. if my div doesn't contain anything a js file will write "no links check in the future."
my html file:
<div id="games" load="checknull(this)"></div>
my js file:
function checknull(id) {
gamelist = document.getElementById(id);
if (gamelist.innerHTML == null) {
gamelist.innerHTML = "No links check in the future"
}
}
But it doesn't work! I've linked the external js file correctly its name and the tag!

There is no load event on a div.
You can achieve the result you're looking for with the onload event of either body or window depending on the rest of your code:
<body onload="checknull(this)">
</body>

I tried this and works for me:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>empty div</title>
</head>
<body>
<div id="games"></div>
<script>
gameList = document.getElementById("games");
window.onload = function () {
if (!gameList.innerHTML) {
return (gameList.innerText = "No links check in the future");
}
};
</script>
</body>
</html>

There is two things that will not work. load handle doesn't exist on div so you could use window.onload and your condition "gamelist.innerHTML == null" will always be false you should use gamelist.innerHTML == "".

First of all, divs don't have event "load", so if you want to wait until the DOM is loaded use document.addEventListener("DOMContentLoaded", callback) instead.
Also, innerHTML and innerText either are strings, not null.
document.addEventListener("DOMContentLoaded", () => {
gamelist = document.getElementById("games");
if (!gamelist.innerHTML) {
gamelist.innerHTML = "No links check in the future"
}
});
<div id="games" load="checknull(this)"></div>

Related

CSS display attribute is set but not visible while code is running

I'm trying to make a CSS Rotator(Loader) visible after pressing a button. Then processing something and afterwards hiding the Rotator. But it seems that while processing the display:block atribute is set
but not visible (See console logs). How could I archive this? Thank you for your help!
Simplified code example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function test(){
$('#loader').css("display","block");
console.log($('#loader').css("display"));
do_something();
console.log($('#loader').css("display"));
$('#loader').css("display","none");
console.log($('#loader').css("display"));
}
function do_something(){
for (var i=0; i<=10E9; i++){
}
}
$(document).ready(function() {
$('#loader').css("display","none");
$('#test_btn').click(test);
});
</script>
</head>
<body>
<div id="loader">Loader</div>
<button id="test_btn">test</button>
</body>
</html>
Browser doesn't update the DOM or change styling until your JS execution halts (which we are achieving using setTimeout. see my code below). That means if you set some element.style.[...] = "...", it won't kick in until your code finishes running (either completely, or because the browser sees you're doing something that lets it intercept processing for a few ms).
JS:
function show() {
$('#loader').css("display", "block");
}
function hide() {
$('#loader').css("display", "none");
}
function newTest() {
show();
setTimeout(() => {
do_something();
hide();
}, 50);
}
function do_something() {
for (var i = 0; i <= 1000; i++) {
console.log('i ', i);
}
}
$(document).ready(function () {
$('#loader').css("display", "none");
$('#test_btn').click(newTest);
});
Html:
<div id="loader">Loader</div>
<button id="test_btn">test</button>
I would suggest to read the answer given by #Mike 'Pomax' Kamermans Here
I just think your :
for (var i=0; i<=10E9; i++){
}
Make your page laggy since it's iterate a lot of time and can't update. Don't really know why.
But if you try to wait with a timer, it's working :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
function test(){
$('#loader').css("display","block");
setTimeout(
function()
{
$('#loader').css("display","none");
}, 1000
);
}
$(document).ready(function() {
$('#loader').hide();
$('#test_btn').click(test);
});
</script>
</head>
<body>
<div id="loader">Loader</div>
<button id="test_btn">test</button>
</body>
</html>

JavaScript Mouse Click addEventListener Not Working

That addEventListener("click", forgotPassword) is not working when // ADD PANEL TO BODY event is calling.
Please Help to fix this.
Javascript:
var forgot_password_btn = document.querySelector("#forgot_password");
var theme_panel = "<div id=\"change-theme\">DARKLIGHT</div>";
if (forgot_password_btn) {
forgot_password_btn.addEventListener("click", forgotPassword);
}
function forgotPassword() {
console.log("clicked");
}
// ADD PANEL TO BODY
window.onload = function () {
document.body.innerHTML += theme_panel;
};
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
Forgot
</body>
</html>
The DOM is not ready when you are fetching the forgot_password element. Therefore, no binding is made. Put the logic inside the onload event:
function forgotPassword() {
console.log("clicked");
}
// ADD PANEL TO BODY
window.onload = function () {
var forgot_password_btn = document.querySelector("#forgot_password");
var theme_panel = "<div id=\"change-theme\">DARKLIGHT</div>";
if (forgot_password_btn) {
forgot_password_btn.addEventListener("click", forgotPassword);
}
};
Also, you should avoid inserting HTML content directly in the JS like that. Put it in the HTML or use templates.

Javascript: onclick function to get elements

I'm trying to get the elements of the clicked source, but I don't know why it isn't working.
JSFIDDLE
HTML:
<span class="populate" onclick="populate();" href="?id=1">Hello</span>
CSS:
.populate {
cursor: pointer;
}
JS:
function populate(event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
The error I see in console is that the function populate is not defined.
Any help or suggestions will be appreciated!
The problem is with the order of the javascript and the span tag.
put the javascript function before the tag
JS
function populate(event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
html
<span class="populate" onclick="populate();" href="?id=1">Hello</span>
We need to define functions before calling them. Fiddle here
http://jsfiddle.net/HdvGD/7/
You code works fine in fiddle. The reason you didn't get it because you wrapped in onload() instead do it in No wrap in Head (fiddle at left top)
your fiddle1
Incase you want in onload() assign like variable
populate = function (event) {
var event = event || window.event;
var src = event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
Check is fiddle2
Check this [answer to find the difference]
Update:
Sorry for pointing depreciated one(I'hv removed it). Event object "event" is not passed from the parameter. Actually here is a simple one
passing the event from onclick like
onclick="populate(event);"
then simple pass it and access like below
function populate(event) {
var src = event.target || event.srcElement;
var href = src.getAttribute('href');
alert(href);
}
Final Fiddle
Anchor tags contain href attribute
<a class="populate" id="link" onclick="populate(this.id);" href="......">Hello
</a>
function populate(id)
{
var someimage = document.getElementById(id);
var mysrc = someimage .src;
}
Use jquery to get it work as simple
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#populate").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var href = $('#populate').attr('href');
alert(href);
event.preventDefault();
});
});
</script>
</head>
<body>
<span class="populate" id="populate" onclick="populate();" href="?id=1" >Hello</span>
</body>
</html>
Your fiddle works fine, on the left-hand side, second drop-down, change to No Wrap - In <head>, now your content is there and script is loaded. Try it again: http://jsfiddle.net/HdvGD/4/

Javascript: Eventhandler not functioning, works in JSFiddle

So this is an answer to another question I posted and I think it is the correct solution. However, while it works wonderfully in jsfiddle it does not function whatsoever outside of that environment. I have tried multiple combinations and I cannot get this thing to work right.
I've tried onLoad in the body, Window.onload both in the header wrapping around the function and separately calling it at the base of the page after all the elements have loaded. Nothing works.
I always get this issue:
Uncaught TypeError: Cannot call method 'addEventListener' of null
Which is frustrating, because all other solutions to this error I have seen revolve around ensuring you do in fact have the specified ID the handler triggers off of in your HTML. Which I do.
I know its probably overkill to make a post here on this but I'm yanking my hair out.
Here's the JSfiddle: http://jsfiddle.net/fFW5r/1/
Here's a mockup page I made to test the concept (which never works):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var link_container = document.getElementById('links');
function myFunction(){ link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
</head>
<body onload="myFunction()">
<div id="links">
Inbound Link
Outbout Link
</div>
<script>window.onload=myFunction()</script>
</body>
</html>
This particular iteration I was trying to test it with the onload call at the bottom of the page after everything had loaded.
var link_container = document.getElementById('links'); need to be executed on document.onload so it has to be inside myFunction
In jsfiddle, the code is executed on load by default. in the fiddle at the left side panel > second select box if you select no wrap - in head you can recreate the problem.
Demo: Fiddle
<script type="text/javascript">
function myFunction(){
var link_container = document.getElementById('links'); // <<-- Move it inside `myFunction()`
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}
</script>
The reason it doesn't work is that you are initializing link_container before the DOM is ready. Then when myFunction() runs, link_container has been initialized to undefined. Which causes it to fail. Initializing it in the function (after the DOM has loaded) should fix the issue
Put declare link_container inside the function.
var link_container = document.getElementById('links');
function myFunction(){
link_container.addEventListener('click', function(e){
if(e.target.nodeName === "A"){
var href = e.target.getAttribute('href'),
selfhost = window.location.hostname;
if(href.indexOf(selfhost) !== -1){
alert('Inbound link clicked');
} else {
alert('Outbound link clicked');
}
}
}, false);
}

How to get the element that fired the "onclick" event

<script>
function clicky(e){
console.log(e) //the clicked element
}
</script>
<span onClick="clicky(this)">Clickable</span>
In the script above, the console.log(e) will give me the <span> that I clicked on.
Is there any way that I could omit the clicky(this) and still get the element?
It's because I don't want to put (this) all over the document.
Any answer are welcomed.
See this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="foo" style="background:blue; width:100px; height:100px">
<script>
function clicky(e){
console.log(e);
}
var foo = document.getElementById("foo");
foo.onclick = function(e){clicky((e || window.event).target);}
</script>
</body>
</html>
You could try this, not tested though.
var spans = document.getElementsByTagName('span');
spans.attachEvent('click'.'clicky');
function clicky(e){
console.log(e) //the clicked element
}
or
var spans = document.getElementsByTagName('span');
for (i in spans)
{
spans[i].attachEvent('click'.'clicky');
}
function clicky(e){
console.log(e) //the clicked element
}
function clicky(e, elem){
<span onClick="clicky(event, this)">Clickable</span>
Or you could use Prototype or jQuery or any other library. I would improve your life.

Categories