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>
Related
I have a multiple div with texts. I have a function that on click (in each part of the screen) change background color and slides text with the next. I also wanted a copy to clipboard button for each poetry and an alert that return a message with "author" returned.
I succeded on click to copy and return the alert message but it applies only to the first div. What is the problem? Is there also a problem of event propagation?
This is the code. I hope someone could give me an insight! Thanks in advance, I'm a newbie :D
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container{
position: relative;
width: auto;
height: 700px;}
.mySlides{
position: absolute;padding: 15px;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
min-width: 50px;
min-height: 50px;
}
body {
transition: background-color 0.5s ease;
}
p {
font-size: 30px;
text-align: left;
color:white;
font-family: 'Baskerville';
}
.author {
padding-top:50px !important;
text-align: right;
}
</style>
</head>
<body>
<div id="btn" class="totale">
<div id="btn" class="container">
<div id="bottone" class="mySlides"><p>Text1</p><p class="author">Author1</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
<div id="bottone" class="mySlides"><p>Text2</p><p class="author">Author2</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
<div id="bottone" class="mySlides"><p>Text3</p><p class="author">Author3</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
</div>
</div>
<script>
/*FUNCTION CHANGE BACKGROUND COLOR AND SLIDES */
var slideIndex = 1;
showSlides(slideIndex);
const button = document.getElementById("btn");
const body = document.body;
const colors = ['#3141AD','#FF9964','#00BAA4','#DF4D44','#514399','#015CCA']
body.style.backgroundColor = colors[0]
button.addEventListener('click',() => {
changeBackground();
plusSlides(1);
});
function changeBackground(){
const colorsIndex = Math.floor(Math.random()*colors.length)
body.style.backgroundColor = colors[colorsIndex]
}
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
/*FUNCTION COPY TEXT*/
function CopyToClipboard(id){
var r = document.createRange();
r.selectNode(document.getElementById(id));
var q = document.createRange();
q.selectNode(document.getElementById('author'));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
try {
document.execCommand('copy');
window.getSelection().removeAllRanges();
alert('Text copied! ' +q +' will thank you');
} catch (err) {
console.log('Unable to copy!');
}
}
</script>
</body>
</html> ```
You have multiple id values that are the same. ids need to be unique across the whole document. Since you are doing document.getElementById(id) you are only returning the first element that matches the id passed.
I would refactor that function, and make use of the event.target, which is a parameter that gets passed to all events, such as "click".
Change buttons to pass in the event to copyToClipboard.
<div id="btn" class="totale">
<div id="btn" class="container">
<div id="bottone" class="mySlides">
<p>Text1</p>
<p class="author">Author1</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
<div id="botttwo" class="mySlides">
<p>Text2</p>
<p class="author">Author2</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
<div id="bottthree" class="mySlides">
<p>Text3</p>
<p class="author">Author3</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
</div>
</div>
And in the function, I change it to camelCase, because PascalCase is loosely reserved for Objects, or other framework specific modules.
Also, you were calling getElementById on "authors", but again, the same problem as before, except this time, those elements have the class of "authors", not id, so it's ok to have more than one per page.
I changed the lookup for authors by using the e.target.previousElementSibling since the author element is just above the button in document order.
function copyToClipboard(e) {
var r = document.createRange()
r.selectNode(e.target)
var q = document.createRange()
q.selectNode(e.target.previousElementSibling())
window.getSelection().removeAllRanges()
window.getSelection().addRange(r)
try {
document.execCommand("copy")
window.getSelection().removeAllRanges()
alert("Text copied! " + q + " will thank you")
} catch (err) {
console.log("Unable to copy!")
}
}
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";
}
}
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>
I am using Aptana Studio 3 text editor and working on Windows 7 Enterprise OS. I have the following AJAX code which is not working on the local system to fetch JSON files kept on an https website. This example is taken from the Youtube video:
JSON and AJAX Tutorial: With Real Examples
index.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta name="test" content="content"/>
<title>JSON and AJAX</title></head>
<header>
<h1>JSON and AJAX</h1>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
</header>
<body>
<script src="main.js"></script>
<button type="button" onclick="function()" id="btn">Fetch Info for 3 New Animals</button>
<div id="animal-info"> </div>
</body>
</html>
Styles.css:
html, body {
padding: 0;
margin: 0;
}
.hide-me {
visibility: hidden;
opacity: 0;
transform: scale(.75);
}
h1 {
margin-top: 0;
font-size: 2.4em;
font-weight: normal;
display: inline-block;
}
body {
font-family: Helvetica, sans-serif;
padding: 50px 10%;
}
button {
background-color: #046380;
color: #FFF;
border: none;
padding: 10px 15px;
font-size: 15px;
border-radius: 4px;
cursor: pointer;
outline: none;
box-shadow: 2px 2px 0 #034154;
margin-bottom: 10px;
margin-left: 18px;
transition: opacity .4s ease-out, transform .4s ease-out, visibility .4s ease-out;
position: relative;
top: -10px;
}
button:hover {
background-color: #034F66;
}
button:active {
background-color: #034154;
box-shadow: none;
position: relative;
top: -8px;
left: 2px;
}
p {
padding: 4px 0 2px 8px;
line-height: 1.7;
border-bottom: 1px dotted #DDD;
list-style: none;
margin: 0;
}
main.js:
var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("onClick", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
//ourRequest.open('GET', 'animals-' + pageCounter + '.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
}
);
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
for (ii = 0; ii < data[i].foods.likes.length; ii++) {
if (ii == 0) {
htmlString += data[i].foods.likes[ii];
} else {
htmlString += " and " + data[i].foods.likes[ii];
}
}
htmlString += ' and dislikes ';
for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
if (ii == 0) {
htmlString += data[i].foods.dislikes[ii];
} else {
htmlString += " and " + data[i].foods.dislikes[ii];
}
}
htmlString += '.</p>';
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
This code doesn't seem to work on my local machine. I tried running it by installing an http-server using NodeJs on my local machine, but still no joy!
Another JSON AJAX code on ww3Schools.com
though seems to work fine. This is an inline javascript code in the html file. Initially i thought onReadyStateChange was the culprit not working on IE, FF, CH etc., but this website code also has onReadyStateChange but it works fine!
Or is it the Button click event handler the cause why it is not working?
btn.addEventListener("onClick", function() {
My code is not inline, could that be the reason? If not, what am i missing or doing wrong?
I modified html file by moving "div" above "script" tag:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="test" content="content"/>
<title>JSON and AJAX</title></head>
<header>
<h1>JSON and AJAX</h1>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" title="no title" charset="utf-8"/>
<button type="button" onclick="function()" id="btn">Fetch Elements</button>
<div id="animal-info"> </div>
</header>
<body>
<script src="main.js"></script>
</body>
</html>
main.js:
var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
// function LoadJSON() {
if (window.XMLHttpRequest) {
// code for modern browsers
var ourRequest = new XMLHttpRequest();
} else {
//code for IE6, IE5
var ourRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// ourRequest.onLoad = function() {
ourRequest.onreadystatechange = function() {
if (this.readyState = 4 && (this.status >= 200 && this.status < 400)) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.open("GET", "https://learnwebcode.github.io/json-example/animals-" + pageCounter + ".json");
// ourRequest.open('GET', 'animals-' + pageCounter + '.json');
ourRequest.send();
ourRequest.onerror = function() {
console.log("Connection error");
};
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
}
);
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
for (ii = 0; ii < data[i].foods.likes.length; ii++) {
if (ii == 0) {
htmlString += data[i].foods.likes[ii];
} else {
htmlString += " and " + data[i].foods.likes[ii];
}
}
htmlString += ' and dislikes ';
for (ii = 0; ii < data[i].foods.dislikes.length; ii++) {
if (ii == 0) {
htmlString += data[i].foods.dislikes[ii];
} else {
htmlString += " and " + data[i].foods.dislikes[ii];
}
}
htmlString += '.</p>';
}
// animalContainer.insertAdjacentHTML('beforeend', htmlString);
animalContainer.innerHTML=htmlString;
}
This works now!
The only problem i am facing is if i have more json files on the server, how do i hide ("hide-me") the button based on the number of json files processed, when button is clicked a no of times?
Right now, it hides button if pageCounter exceeds 3.
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
The other issue i see is if i enable "insertAdjacentHTML", it displays each json twice. Why is this happening?
// animalContainer.insertAdjacentHTML('beforeend', htmlString);
Use this:
btn.style.visibility = "hidden";
How do use this image:
http://h899310.devhost.se/proxy/newProxy/uplfile.png
Instead of the regular:
<input type="file" />
Have a look at Styling an input type="file".
I'm not very sure on whether you want to style file upload fields, or whether you simply want to use a png file in a style.
Quirksmode.org has a section on styling file upload fields though, that you would want to refer to.
If you want to use the PNG file to use in a style inside a page, you should like at how to set backgrounds using images, although this may not work for all HTML elements.
I did something like this and it worked perfectly!
<script type="text/javascript">
var t = 0;
var IE = navigator.appName;
var OP = navigator.userAgent.indexOf('Opera');
var tmp = '';
function operaFix() {
if (OP != -1) {
document.getElementById('browser').style.left = -120 + 'px';
}
}
function startBrowse() {
tmp = document.getElementById('dummy_path').value;
getFile();
}
function getFile() {
// IF Netscape or Opera is used...
//////////////////////////////////////////////////////////////////////////////////////////////
if (OP != -1) {
displayPath();
if (tmp != document.getElementById('dummy_path').value && document.getElementById('dummy_path').value
!= '') {
clearTimeout(0);
return;
}
setTimeout("getFile()", 20);
// If IE is used...
//////////////////////////////////////////////////////////////////////////////////////////////
} else if (IE == "Microsoft Internet Explorer") {
if (t == 3) {
displayPath();
clearTimeout(0);
t = 0;
return;
}
t++;
setTimeout("getFile()", 20);
// Or if some other, better browser is used... like Firefox for example :)
//////////////////////////////////////////////////////////////////////////////////////////////
} else {
displayPath();
}
}
function displayPath() {
document.getElementById('dummy_path').value = document.getElementById('browser').value;
}
</script>
<style type="text/css">
#browser
{
position: absolute;
left: -132px;
opacity: 0;
filter: alpha(opacity=0);
}
#browser_box
{
width: 104px;
height: 22px;
position: relative;
overflow: hidden;
background: url(button1_off.jpg) no-repeat;
}
#browser_box:active
{
background: url(button1_on.jpg) no-repeat;
}
#dummy_path
{
width: 350px;
font-family: verdana;
font-size: 10px;
font-style: italic;
color: #3a3c48;
border: 1px solid #3a3c48;
padding-left: 2px;
background: #dcdce0;
}
</style>
<body onload="operaFix()">
<div id="browser_box">
<input type="file" name="my_file" id="browser" onclick="startBrowse()" />
</div>
</body>