How to automatically generate a range of buttons with pre-determined onclick events? - onclick

I am trying to generate a button from a range X; in this case, from 0 to 25, and when I click in one generate button, it will alert the word eggs. I followed the rules to generate an on click event on an element through JavaScript, but the code didn't work. What is wrong with the code?
The code is in the link. Unfortunately, I couldn't upload it through CTRL+K stackoverflow feature.
https://textuploader.com/1gynb

Hei,
Not a javascript expert but I think this does what you want:
<p id='ai'>Click the button to make a BUTTON element with text.</p>
<button onclick="generator()">Try it</button>
<script>
function generator() {
for (var x = 0; x < 26; x++) {
var btn = document.createElement("BUTTON");
btn.innerHTML = x;
btn.setAttribute("onclick", "myFunction();");
document.getElementById('ai').innerHTML += btn.outerHTML;
}
}
function myFunction() {
console.log("done")
}
</script>

Related

Making a button that shows or hides multiple images in a random location

I have a problem when I am making the website for one gallery.
I made the code for the button that can show and hide multiple images.
I intend to make the button can place several images in randomly.
I write the code that can function for only one image.
Please tell me the code that functions as a button to place multiple images in a random location.
Users can hide images by pressing the button.
And when users press the button again, it places the images in another random location.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("color");
btn.addEventListener("click", () => {
let randY = Math.floor((Math.random() * height) + 1);
let randX = Math.floor((Math.random() * width) + 1);
box.style.top = randY + "px";
box.style.right = randX + "px";
});
function showhide() {
var x = document.querySelectorAll("#color");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
You're doing the correct thing in showHide() when using querySelectorAll. You are then able to get all images.
You should never have elements with the same ids. They should be unique. So querySelectorAll("#color") works, but it's now how you should do. Do a querySelector on "img.random" instead.
getElementById only returns a single element, not like querySelectorAll. So you need to use querySelectorAll('img.random').
This might be beyond your knowledge, I don't think you should add the images in HTML, but in javascript code.
a) Add all image paths in an array: ['https://image.com/image.png', ...]
b) Add a single img element. <img id="template" class="random">
c) In javascript code, clone that element for each image path in the array. You can use cloneNode for this.
d) Randomize each position for each element, just like you have done now.
e) Add each element to the DOM through appendChild. Have a unique div that you append to. Be sure to clear it every time second time you hit the button.
f) Solve all bugs along the way. :P
The problem
The main issue here is that you're using getElementById to query #color
const box = document.getElementById("color");
Since getElementById only returns one element (but you have two in your DOM) and the style only applies to one element. That's why you're seeing only one element is randomly moving and the other just stay in the same place.
A side note here, id should be unique in a DOM.
You're in fact using the correct API for the job in the showhide function
var x = document.querySelectorAll("#color");
The fix:
To fix this, you need to query all images by their classname (as suggested in the side note, don't use id for the job)
const boxes = document.querySelectorAll(".random");
Now we have a node list, as you do in the showhide function, we need to loop thru it, I'm not using a for loop here, instead, a forEach loop, it's just more terser and a modern addition to the JS
// Since boxes are not array, we need to covert it to array so we can use that handy `.forEach` here:
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
Now, this should fix your issue. See the complete code below.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/100/100/">

Set a button to disable after the first click using css

I'm working on this form:
https://app.couponreach.co/view-form/869/582
And I'm looking to disable the button after the first click.
The only code I can add is a css code.
Is that possible?
I'm thinking of something like:
.btncustom:afterclick {
pointer-events:none;
}
Anything to disable the button after the first click, pointer-events is an option or to make it grayed out once clicked.
Since you're asking for a javascript solution as well, here:
UPDATE: used getElementsByClassName to disable all buttons on click of any other button.
var buttons = document.getElementsByClassName("btn-custom");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
for(var j = 0; j < buttons.length; j++) {
buttons[j].disabled = true;
buttons[j].style.opacity = 0.5;
}
})
}
<button class="btn-1 btn-custom">Button 1</button>
<button class="btn-2 btn-custom">Button 2</button>
<button class="btn-3 btn-custom">Button 3</button>
<button class="btn-4 btn-custom">Button 4</button>
CSS
.btncustom:disabled {
pointer-events: none;
}
Javascript
document.getElementByClass("btncustom").disabled = true;
This code will disable the button which is enough to disable its pointer-events, but added the CSS to make it clear that you can style the disabled button (opacity, color, font or whatever)

Use CSS to move cursor to another element

I'm trying to move the location of the cursor (mouse pointer) when an element is brought into view.
Let's say I have a button at the top of screen that, on click, opens a somewhere else on the screen. They are not connected in the doc flow (the is position: fixed>
When I show the new item, I want the mouse cursor to move to the newly displayed element, e.g. to the close button inside of it. I added a call to focus() but not working...
function myClick(idName) {
let listOfBios = document.getElementsByClassName("contents");
const len = listOfBios.length;
let elemName = "Content_" + idName;
let elem = document.getElementById(elemName);
elem.focus();
for(let i = 0; i < len; i++) {
let theBio = listOfBios[i];
if(theBio != elem){
//alert(elemName);
theBio.classList.remove("show_contents")
}
}
elem.classList.toggle("show_contents", 1);
elem.focus();
}
Assume that the rest of the code works, so I definitely have the right element ad toggle() is working.
You will need JS to achieve this. See below for example with vanilla JS.
in your view:
<input type="text" id="myTextField" value="Text field.">
in JS:
document.getElementById("myTextField").focus();
Check this fiddle:
https://jsfiddle.net/jz7v53tL/
Looks like it can't be done with just CSS and JS. Trying to close this out, I hope this is how.

How to flow a working clock into text?

I am trying to place a live clock into a body of text. I need it to flow as if it were just part of the text, but still be live to the local device. Playing around in Adobe Muse I have been able to get a clock into the text, but it segregates itself to its own line rather than flowing like part of the paragraph.
Following is the code Muse produced. I assume I need to make a change to either actAsInlineDiv normal_text, or actAsDiv excludeFromNormalFlow, or both, but how?
<p id="u3202-10"><span class="Character-Style">You look at the clock on this device and it reads </span><span class="Character-Style"><span class="actAsInlineDiv normal_text" id="u13390"><!-- content --><span class="actAsDiv excludeFromNormalFlow" id="u13388"><!-- custom html --><html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
m=checkTime(m);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
</span></span></span><span class="Character-Style">As a result you believe that this is the time. As it happens this is the time but unknown to you your device's clock has stopped functioning and is stuck. Does your true belief that this is the time count as knowledge?</span></p>
I don't know about Muse, but if all you want is a clock of the current time running inline with some text you could do this:
window.onload = displayTime;
function displayTime() {
var element = document.getElementById("clock");
var now = new Date();
var options = {hour: '2-digit', minute:'2-digit'};
element.innerHTML = now.toLocaleTimeString(navigator.language, options);
setTimeout(displayTime, 1000);
}
The current time is <span id="clock"></span> and it's inline with text.
EDIT
I added these two lines to remove the seconds from display as you requested in your comment.
var options = {hour: '2-digit', minute:'2-digit'};
element.innerHTML = now.toLocaleTimeString(navigator.language, options);

Scroll an iframe without having to mouse over it

I have an iframe that I use to display the main content of my webpage; however, I would like to make the IFRAME scroll regardless of where the mouse is pointing. I do not want my visitors to be confused by not being able to scroll unless their mouse is over the iframe. Is this possible? To scroll the iframe with the mouse hovering anywhere over the body?
I won't link any code, because the only relevant code I have is the < iframe>< /iframe> tag.
(the body itself is not scrollable with scrollbars hidden)
Alright. I put together a rather quick and dirty solution for this which includes the following steps:
Add an "id" to your <iframe> element. (In my example I used id="myFrame")
Attach the jQuery Mousewheel plugin to the header of your html page along with the latest jQuery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://raw.github.com/brandonaaron/jquery-mousewheel/master/jquery.mousewheel.js"></script>
Finally add the following javascript code at the end of the html body or after the iframe itself.
<script type="text/javascript">
var scrolloffset = 30; // amount of scrolling per mousewheel step
var myFrame = $('#myFrame'); // the iframe ID
var frameScrollPosition = 0;
$(window).mousewheel(function(event,delta){
// reset stored offset so that it matches with iframe's
frameScrollPosition = myFrame.contents().scrollTop();
var frameHeight = myFrame.contents().height() - myFrame.height();
if(delta > 0){
var newPosition = frameScrollPosition - scrolloffset;
} else {
var newPosition = frameScrollPosition + scrolloffset;
}
if(newPosition < 0){
newPosition = 0;
}
if(newPosition >= frameHeight){
newPosition = frameHeight;
}
frameScrollPosition = newPosition;
myFrame.contents().scrollTop(frameScrollPosition);
});
</script>
Make sure you download the plugin and not call it from github like me. It was just for testing and proof of concept.

Resources