How to make the image swap every second - html

This code will turn the bulb on/off but i want to make the lightbulbs keeps flashing. I've tried different methods and nothing works
<!DOCTYPE html>
<html>
<body>
<img id="bulb" onclick="switch()" src="off.png" width="100" height="180">
<p>On/Off</p>
<script>
function
switch () {
var image = document.getElementById('Bulb');
if (image.src.match("on")) {
image.src = "off.png";
} else {
image.src = "on.png";
}
}
</script>
</body>
</html>

Here is an example, using setInterval(). I have swapped the image to a div thats background changes color, but same principal applies.
I think its also worth pointing out that you could also do this with a css animation and then just use javascript to toggle the class onto the element. But assuming you just wanna stick to JS for now:
let flashInterval = null;
let flashSpeed = 100;
let bulb = document.getElementById('bulb');
function toggleBulb() {
if (bulb.classList.contains('on')) {
bulb.classList.remove('on');
} else {
bulb.classList.add('on');
}
}
function flashBulb() {
if (flashInterval === null) {
flashInterval = setInterval(() => {
toggleBulb();
}, flashSpeed);
} else {
clearInterval(flashInterval);
flashInterval = null;
}
}
document.getElementById('toggleBlub').addEventListener('click', toggleBulb);
document.getElementById('toggleFlash').addEventListener('click', flashBulb);
#bulb {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid #ccc;
background: transparent:
}
.on {
background: #fcba03;
}
<div id="bulb" class=""></div>
<br>
<button id="toggleBlub">Bulb On/Off</button>
<br><br>
<button id="toggleFlash">Flash On/Off</button>

in my opinion, don't use setInterval but u can use a CSS animation rather than it.

You should know about js event and js reserve keyword and be sure to use good code editor so that you can see your error.
I see you trying to keep flashing but you used onclick event that is clickable it will not flashing.
here is the code below, which you want,
<!DOCTYPE html>
<html>
<body>
<img id="bulb" src="off.jpg" width="100" height="180">
<p>On/Off</p>
<script>
var myImage = document.querySelector('#bulb');
var update = setInterval(myUpdate, 1000);
function myUpdate() {
setTimeout(() => {
if (myImage.src.match('off.jpg')) {
myImage.src = 'on.jpg'
} else {
myImage.src = 'off.jpg'
}
}, 500)
}
</script>
</body>
</html>
or you can use onclick event, when you click than it will start flashing
here is the code below
<!DOCTYPE html>
<html>
<body>
<img id="bulb" onclick="mySwitch(this)" src="off.jpg" width="100" height="180">
<p>On/Off</p>
<script>
function mySwitch(myImage) {
var update = setInterval(myUpdate, 500);
function myUpdate() {
setTimeout(() => {
if (myImage.src.match('off.jpg')) {
myImage.src = 'on.JPG'
} else {
myImage.src = 'off.jpg'
}
}, 100)
console.log(myImage)
}
}
</script>
</body>
</html>

I changed your function name to switchBulb because switch is reserved
var intervalID = window.setInterval(switchBulb, 1000);
function switchBulb() {
var image = document.getElementById('bulb');
if (image.src.match("on")) {
image.src = "off.png";
} else {
image.src = "on.png";
}
}

Related

how to make a loading animation with my code

I can't seem to figure out how to make the boxes rotate. I tried transformation, JS, and even html special code. I do suck at CSS, so this is my code so far:
<!DOCTYPE html>
<html>
<head>
<script>
//great code from Scriptkiddy1337 on stack overflow
const pageStack=[];
function getParameterByName(name, url) {
url = url || window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
window.addEventListener('load', function (e) {
var templates = document.getElementsByClassName('sitecontent');
for (var i = 0, v; v = templates[i]; i++) {
for (var j = 0, x; x = v.childNodes[j]; j++) {
if (x.nodeType === Node.ELEMENT_NODE) {
pageStack.push(x);
}
}
}
var pageIndex = getParameterByName('page') || '0';
loadPage(pageIndex);
});
function loadPage(index) {
if (index >= pageStack.length || index < 0) {
document.body.innerText = '404 Page not found';
return;
}
document.body.innerHTML = '';
document.body.appendChild(pageStack[index]);
}
</script>
<style>
box{
transition: 3s;
width:50px;
height:50px;
position:fixed;
transform:/*im confused here*/;
}
</style>
</head>
<body>
<pageholder class="sitecontent">
<page>
<animator>
<!--I want them to rotate in a circle-->
<box style="background-color:red">.</box><br><br><br>
<box style="background-color:red">.</box><br><br><br>
<box style="background-color:red">.</box><br><br><br>
</animator>
Next Page
</page>
<page>
<h1>Homepage</h1>
<hr>
<p>Need help :(</p>
</page>
</pageholder>
</body>
</html>
I tried to transform CSSstuff, JS animations (which I also kinda suck at), and even special HTML code. I might be missing something, but as far as I know (which isn't a lot, unfortunately), I have done nearly everything I can think of.
I would highly recommend you read up on CSS Animations
<style>
/* The animation code */
#keyframes rotateBox {
to {transform: rotate(360deg)}
}
box{
transition: 3s;
width: 50px;
height: 50px;
position: fixed;
/* Use the animation here */
animation: rotateBox 3s;
}
</style>

How to force browsers to preload image with display: none?

Firefox will not load images with display: none until they are required to be shown to the user. Chromium will stall until the image is loaded, and then display it.
With smaller file sizes, there is a brief flash if the image is not already loaded on Firefox. With larger file sizes, there is a much longer delay that will also make Chromium's stall noticeable.
I would like to have images with display: none preloaded so there is no delay when displaying them.
I have tried using Javascript to declare a new Image object, but this does not work with Firefox or Chromium.
You can cycle between images in this example with the right and left arrow keys.
<!DOCTYPE html>
<html>
<head>
<style>
body, html {
height: 100%;
margin: 0;
padding: 0;
}
.imgs {
width:50%;
height: 50%;
}
</style>
</head>
<body>
<img src="https://picsum.photos/200/100" style="display: block;" class="imgs">
<img src="https://picsum.photos/200/200" style="display: none;" class="imgs">
<script>
imgs = document.getElementsByClassName("imgs");
// THIS DOES NOT WORK
//~ function preloadImage(url)
//~ {
//~ var img = new Image();
//~ img.src = url;
//~ }
//preloadImage("myImg.jpg"); THIS DOES NOT WORK
document.onkeydown = checkKey; // directional keys
function checkKey(e) {
if (document.activeElement.tagName != "INPUT") {
e = e || window.event;
switch (e.keyCode) {
case 38:
// up arrow
break;
case 40:
// down arrow
break;
case 37:
// left arrow
imgs[0].style.display = "block";
imgs[1].style.display = "none";
break;
case 39:
// right arrow
imgs[0].style.display = "none";
imgs[1].style.display = "block";
break;
}
}
}
</script>
</body>
</html>
I have figured out my own solution to this problem.
I use a class called "imgBuffer" to hold images that need to be displayed immediately. Images of this class will hold the source of images that need to be readily displayed, but will not display the images themselves.
The tricky part is making sure the hidden images are in a location on screen that does not affect the layout in any way.
Notice the width and height of the hidden buffered image matches that of the displayed images. If you adjust the dimensions of the hidden image, the page may behave differently such as adding a scrollbar when it's not really necessary.
<!DOCTYPE html>
<html>
<head>
<style>
body, html {
height: 100%;
margin: 0;
padding: 0;
}
.imgs {
width:50%;
height: 50%;
}
.imgBuffer {
position: absolute;
height: 50%;
width: 50%;
visibility: hidden;
z-index: -1;
}
</style>
</head>
<body>
<img src="https://picsum.photos/200/100" style="display: block;" class="imgs">
<img src="https://picsum.photos/200/200" style="display: none;" class="imgs">
<img src="https://picsum.photos/200/100" class="imgBuffer">
<img src="https://picsum.photos/200/200" class="imgBuffer">
<script>
imgs = document.getElementsByClassName("imgs");
// THIS DOES NOT WORK
//~ function preloadImage(url)
//~ {
//~ var img = new Image();
//~ img.src = url;
//~ }
//preloadImage("myImg.jpg"); THIS DOES NOT WORK
document.onkeydown = checkKey; // directional keys
function checkKey(e) {
if (document.activeElement.tagName != "INPUT") {
e = e || window.event;
switch (e.keyCode) {
case 38:
// up arrow
break;
case 40:
// down arrow
break;
case 37:
// left arrow
imgs[0].style.display = "block";
imgs[1].style.display = "none";
break;
case 39:
// right arrow
imgs[0].style.display = "none";
imgs[1].style.display = "block";
break;
}
}
}
</script>
</body>
</html>

dragleave event is firing on inner childs

I am trying to use HTML5 drag and drop and make the dropable container to change its style when the draggable element is over it.
the problem is if the dropable container contain inner elements a dragleave events getting fired making the container to lose its style.
as you can see when the draggable element is getting inside the small green box. we lose the red border of the outside div.
<html>
<head>
<style>
.droptarget {
width: 100px;
height: 100px;
margin: 15px;
margin-right: 100px;
padding: 10px;
border: 1px solid #aaaaaa;
}
.inner-droptarget {
margin-left: 20px;
margin-top: 20px;
width: 50px;
height: 50px;
border: 1px solid green
}
</style>
</head>
<body>
<p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag me!</p>
<div class="droptarget" ondragenter="dragEnter(event)" ondragleave="dragLeave(event)" ondrop="drop(event)" ondragover="allowDrop(event)">
<div class="inner-droptarget">
</div>
</div>
<script>
function dragStart(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function dragEnter(event) {
if ( event.target.className == "droptarget" ) {
event.target.style.border = "3px dotted red";
}
}
function dragLeave(event) {
if ( event.target.className == "droptarget" ) {
event.target.style.border = "";
}
}
</script>
<p>
The border of the outside div should remain red even if dragging into the green div!
</p>
</body>
</html>
You have to ignore "dragleave" events that are fired on elements that are contained in "droptarget" (for example "inner-droptarget").
To do so, you can detect if the event was fired from a descendant of the drop area. Your handler will look like this:
function dragLeave(event) {
if ( event.target.className == "droptarget" ) && !($('.droptarget').contains(event.fromElement) {
event.target.style.border = "";
}
}
When you enter the inner div during dragging, the event drag enter and then drag leave event is firing. We need a way to mark that you are leaving the outer div and entering the inner div so the border stays red on the outer div.
I can get both borders to be red, but when you leave its a similar problem, both borders go back to green.
<body>
<p ondragstart="dragStart(event)" draggable="true" id="dragtarget">Drag me!</p>
<div id="myOuterDiv" class="droptarget" ondragenter="dragEnter1(event)"
ondragleave="dragLeave1(event)"
ondrop="drop(event)"
ondragover="allowDrop(event)">
<div id="myInnerDiv" class="inner-droptarget" ondragenter="dragEnter2(event)"
ondragleave="dragLeave2(event)">
</div>
</div>
<script>
var inOuter = false;
var inInner = false;
function dragStart(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function dragEnter1(event) {
inOuter = true;
document.getElementById("myInnerDiv").addEventListener("ondragenter", dragEnter2);
console.log("entered outer");
return highlightBorder();
}
function dragLeave1(event) {
console.log("left outer");
inOuter = false;
highlightBorder();
event.preventDefault();
}
function dragEnter2(event) {
console.log("entered inner");
inInner = true;
inOuter = true;
return highlightBorder();
}
function dragLeave2(event) {
console.log("left inner");
inInner = false;
inOuter = true;
return highlightBorder();
}
function allowDrop(ev) {
return false;
}
function drop(event) {
var inOuter = false;
var inInner = false;
document.getElementById("myInnerDiv").style.border ="3px solid green";
document.getElementById("myOuterDiv").style.border ="3px solid green";
return false;
}
function highlightBorder() {
if( inInner)
{
document.getElementById("myInnerDiv").style.border ="3px dotted red";
document.getElementById("myOuterDiv").style.border ="3px dotted red";
return false;
}
if(!inInner && inOuter)
{
document.getElementById("myInnerDiv").style.border ="";
document.getElementById("myOuterDiv").style.border ="3px dotted red";
return false;
}
if(!inInner && !inOuter)
{
document.getElementById("myInnerDiv").style.border ="";
document.getElementById("myOuterDiv").style.border ="";
return false;
}
}
</script>
<p>
The border of the outside div should remain red even if dragging into the green div!
</p>
</body>
</html>
You can use a counter to solve the problem.When dragenter counter++,when dragleave counter-- and check counter === 0 then do something.
// div has an child element
divEl.addEventListen("dragenter",dragEnter)
divEl.addEventListen("dragleave",dragLeave)
counter = 0
function dragEnter(){
counter++
}
function dragLeave(){
counter--
if(counter === 0){
// then do something
}
}

Printing what is inside a modal

I have a modal where I want to print the full contents of it. I don't want anything else printed aside what is within the modal.
Here I created the button within the modal:
This should not be printed...
<button id="btnPrint">Print (this btn should not be printed!)</button>
<hr />
<div id="printThis">
This should BE printed!
</div>
<div id="printThisToo">
This should BE printed, too!
</div>
I have some text next to the button, but this text should not show when you click the button to preview the print view.
Here I wrote some js to show what content should be printed:
document.getElementById("btnPrint").onclick = function() {
printElement(document.getElementById("printThis"));
printElement(document.getElementById("printThisToo"), true, "<hr />");
window.print();
}
function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof(delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof(delimiter) === "object") {
$printSection.appendChlid(delimiter);
}
}
$printSection.appendChild(domClone);
}
Finally, I wrote some css:
#media screen {
#printSection {
display: none;
}
}
#media print {
body {
font-family: 'Open Sans', sans-serif;
font-size: 12px;
font-weight: 500;
color: #101010;
background: #f6f5fa;
visibility:hidden;
}
#printSection, #printSection {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
When I click the button in the modal, nothing happens and no errors appear in the console. Not sure what the issue is. Any help would be much appreciated.
UPDATED CODE:
(HTML)
<div>
This should not be printed...
<button ng-click="printPreview()">Print (this btn should not be printed!)</button>
</div>
<hr />
<div id="printThis">
This should BE printed!
</div>
(JS)
var app = angular.module('dmdesktop');
app.controller('PrintViewCtrl', rollUpCtrl);
rollUpCtrl.$inject = ['$scope', '$rootScope', '$http', '$uibModal','headersvc','locFiltersvc']
function rollUpCtrl($scope, $rootScope, $http, $uibModal, headersvc, locFiltersvc) {
$scope.printPreview = function() {
printElement(document.getElementById("printThis"));
}
function printElement(elem) {
alert ("printing!");
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
$printSection.innerHTML = "";
$printSection.appendChild(domClone);
window.print();
}
}
(CSS)
same as before
With the updated code and window.print inside a evalAsync function allows you to print the content inside a modal
$scope.$evalAsync(function () {
window.print();
});

Is there a way to make a textbox auto expand without jQuery?

I have set resize to vertical but I would like that when the user fills the textbox then its size expands down. Is there any way this can be done without using an external library like jQuery?
Only in CSS and contentEditable="true" attribute.
div {
display:inline-block;
border: solid 1px #000;
min-height: 200px;
width: 300px;
}
Demo Here
This has been answered here already: Creating a textarea with auto-resize
<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
border: 0 none white;
overflow: hidden;
padding: 0;
outline: none;
background-color: #D0D0D0;
resize: none;
}
</style>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function init () {
var text = document.getElementById('text');
function resize () {
text.style.height = 'auto';
text.style.height = text.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
text.focus();
text.select();
resize();
}
</script>
</head>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>
Example: https://jsfiddle.net/hmelenok/WM6Gq/
Credits go to panzi, vote him up here: https://stackoverflow.com/a/5346855/1540350