Can't figure out why the loop is not working - javascript

I know that there are countless questions about for loops or equivalent in JavaScript but I can't figure out how to make this one work.
<!-- Comes from https://github.com/sindresorhus/screenfull.js/edit/master/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/screenfull.js/5.0.2/screenfull.min.js"></script>
</head>
<body>
<img id = "img1" src="https://placeimg.com/200/150/nature" alt="">
<img id = "img2" src="https://placeimg.com/200/150/nature/2" alt="">
<button id="test">Click</button>
<script>
// WORKS:
// $(function () {
// $('#img1').click(function () {
// screenfull.request($('#img1')[0]);
// });
// });
var ids = ["#img1", "#img2", "#test"];
var item;
for (item of ids) {
$(function () {
$(item).click(function()) {
screenfull.request($(item)[0]);
}
})
}
</script>
</body>
</html>
Expected output: clicking on either of the two images should put it fullscreen.
Any idea? (I started with a for loop but I accept other solutions.)
I won't know the number of items in advance (nor their names) so the solution has to work with this specificity.

Just make a selector with both ids
$('#img1, #img2').click(function () {
screenfull.request(this);
});
with an array
var imgs = ['#img1', '#img2'];
$(imgs.join(',')).click(function () {
screenfull.request(this);
});
if you want to loop and reinvent what jQuery does for you
var imgs = ['#img1', '#img2'];
imgs.forEach(function(id){
$(id).click(function () {
screenfull.request(this);
});
});

Related

How do i use javascript to manipulate empty divs?

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>

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>

click event for links

I have the following HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
Something
<div id="foo></div>
<script>
$(function() {
$link = $("#bar");
$link[0].click(function() {
alert("Whatever.");
});
});
</script>
</body>
</html>
This article explains the approach. However it's not working - no alertbox shows. Any ideas?
Just remove the [0] array index from the code and make sure to close div id quotes:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
Something
<div id="foo"></div>
<script>
$(function() {
$link = $("#bar");
$link.click(function() {
alert("Whatever.");
});
});
</script>
</body>
</html>
the $link[0] will return native element not jQuery object, use onclick event or addEventListener('click', ....)
$(function() {
$link = $("#bar");
$link[0].onclick = function() {
alert("Whatever.");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Something
<div id="foo"></div>
and the correct way to select element by index using jQuery is using eq()
$(function() {
$link = $("#bar");
$link.eq(0).click(function() {
alert("Whatever.");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Something
<div id="foo"></div>
please note that selector ID will only return 1 element so you can use second index or greater.
If you want to not open link but only alert any text you can try to write script something like that:
$('#bar').click(function(e) {
e.preventDefault();
alert('Whatever.');
})
If you are using id as a common selector than you are doing bad, please use class for common selector else you don't need to do something like $(id)[0]. Also, make a habit of unbinding the event once the binding is done.
$(function() {
$link = $("#bar");
$link.off('click').on('click', function() {
let $this = $(this);
let href = $this.attr('href');
alert("href " + href);
});
});

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.

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