How can i put it background image on setAttribute method? - javascript

I'm making a simple program that cuts the circle evenly.
enter image description here
and I want to put it image using 'setAttribute' method.
but, It doesn't work as i thought.
here is my code.
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0; padding:0;}
</style>
<script>
function elt(name, attributes){
var node = document.createElement(name);
if( attributes ){
for(var attr in attributes){
if(attributes.hasOwnProperty(attr)){
node.setAttribute(attr,attributes[attr]);
}
}
}
for(var i=2; i<arguments.length; i++){
var child = arguments[i];
if( typeof child == "string" ){
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
window.onload=()=>{
const IMG_W_COUNT = 50;
const IMG_H_COUNT = 33;
const IMG_SUM = 1650;
for(var i=1,j=0;i<=IMG_SUM;i++,j+=18){
var ImageSaver = elt("div",{
class:"menu item"+i,
width:18+"px",
height:18+"px",
background:"url('paint.jpg')",
backgroundPosition:0+"px"+" "+j+"px"
});
document.body.appendChild(ImageSaver);
}
}
</script>
</head>
<body>
</body>
</html>
The elt function is a function that helps to easily generate an element.
I'd really appreciate your help.

background, height and width aren't attributes (except on a few elements, and there they are mostly deprecated), nor is backgroundPosition.
To set a CSS property value with a function use setProperty on a style declaration.
Make sure you use the CSS property name, which is background-position not backgroundPosition.
element.style.setProperty("name", "value");

You have to set CSS properties.
element.style.width=18+"px";
element.style.height=18+"px";
element.style.background="url('paint.jpg')";
element.style.backgroundPosition="top right";

Related

I have multiple lines of text that print in typewriter animation. However, when I refresh my browser the different lines of texts get mixed up

I have multiple lines of text that print in typewriter animation, but when I refresh my browser the different lines of texts get mixed up.
Something like this "****eI icsr eAahtmeedr .t hWiesl cWoembes ittoe muys iWnegb sHiTtMeL,. CSS, and JS.**"
Click around Run snippet 5 or 6 times and including the code buttons, and you will see it see the problem.
The intro is a automatic animation when you first land the page which reads "Hello! My name is Frank. Welcome to my Website."
Tell Me More button prints out "I created this Website using HTML, CSS, and JS."
Nice! button prints out "This website is to showcase my skills."
Ok prints out "You should hire me. Scroll down to see why."
This is just a template. I am actually very new to Java and getting familiar with CSS and HTML. I am creating a portfolio and also learning to code, so bear with me.
I am basically trying to copy this website here https://www.amysboyd.com
I would like the buttons to disappear like in the website, but I don't know how to do that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portfolio</title>
<link rel="stylesheet" href="Portfolio Styles.css" </head>
<body>
<div class="abouttextsection">
<h1 id='output'></h1>
<script>
var a = 0;
var introtxt = 'Hello! My name is Frank. Welcome to my Website.';
var speed = 50;
function aboutintro() {
if (a < introtxt.length) {
document.getElementById("output").innerHTML += introtxt.charAt(a);
a++;
setTimeout(aboutintro, 50);
}
}
window.onload = aboutintro;
var doc, bod, I, TypeMaker; // for use on other loads
addEventListener('load', function() {
doc = document;
bod = doc.body;
I = function(id) {
return doc.getElementById(id);
}
TypeMaker = function(element, interval) {
this.element = element;
this.interval = interval || 50;
var t = this,
r;
this.type = function(string) {
if (r) clearInterval(r);
var s = string.split(''),
l = s.length,
i = 0;
var p = 'value' in this.element ? 'value' : 'innerHTML';
this.element[p] = '';
r = setInterval(function() {
t.element[p] += s[i++];
if (i === l) {
clearInterval(r);
r = undefined;
}
}, t.interval);
}
}
var typer = new TypeMaker(I('output')),
First_test = I('First_test'),
Second_test = I('Second_test'),
Third_test = I('Third_test');
var testArray = [''];
var testArrayL = testArray.length;
First_test.onclick = function() {
typer.type('I created this Website using HTML, CSS, and JS.');
}
Second_test.onclick = function() {
typer.type('This website is to showcase my skills.');
}
Third_test.onclick = function() {
typer.type('You should hire me. Scroll down to see why.');
}
});
</script>
<div class="aboutsectionbutton">
<button id='First_test' type='button' value='Tell Me More' />Tell Me More</button>
<button id='Second_test' type='button' value='Nice!' />Nice!</button>
<button id='Third_test'>Ok</button>
</div>
</div>
</body>
</html>
Add fadeOut transition to css class ->
CSS:
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s .25s, opacity .25s linear;
}
And on click event just add this class ->
JS:
Second_test.onclick = function() {
this.classList.add('hidden')
typer.type('This website is to showcase my skills.');
}
jsfiddle

How to track clicks of a button?

I’m trying to track the clicks on a button on my website. I’ve tried adding the following but to no success. I’m a noob to JS..
function trackButton(e) {
onPage.innerHTML = ++i;
}
var i = 0;
var onPage = document.getElementById(‘track’);
var clickCount = document.getElementById(‘bttn’);
clickCount.addEventListener('click', function (e) {
addOne(e);
}, false);
You did some mistake:
The function addOne doesn't exist, it's trackbutton
it's i++ to increment a value, not ++i
And some tips for you:
Use let and const (ES6) for the variable, not var
And the e for the event is useless here, you are not using it, so it's not mandatory here
Do these change and it must work !
UPDATE:
To increment a value ++i works, see the documentation
Change the quotes ‘‘ with " " or ' '.
Like so: document.getElementById(‘track‘) to document.getElementById('track')
I was checkin your code and its almost all right, i think that the problem its in your addOne function, here is a way to resolve the problem.
i creat the button and paragraph elements in html and in javascript a variable n where we are going to storage the clicks tha the user did and we increment n when the function its called in the button's event
var n = 0;
var button = document.getElementById('track');
button.addEventListener('click', trakeo);
var texto = document.getElementById('number');
function trakeo(){
n++
texto.innerHTML = n;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A Great Demo on CodePen</title>
</head>
<body>
<button id="track">Button</button>
<p id="number"></p>
</body>
</html>
Try to use
addEventListener('click',)
https://www.w3schools.com/jsref/met_element_addeventlistener.asp

Problem with slideshow in Javascript, images don't load

I've a problem with a slider I've to do for school.
The console return no error, but the images don't show in the slider. I'm on it for four days now and I can't figure out what is the problem, so it seems that I need your lights ! ^^
I used the console to check if "diaporama.js" is working and it is, the console.log at the end of "slider.js" is to check if my image path is ok and it is. I've absolutely no clue of what is going wrong.
Thank you in advance !
Here is my code :
HTML
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta property="og:url" content="" />
<title>Slider</title>
<link rel="stylesheet" href="slide.css">
</head>
<body>
<h1>Test</h1>
<div id="caroussel">
<img src="" alt="diapo1" id="diapo">
<div id="precedent" ><</div>
<div id="suivant" >></div>
</div>
<script src="diaporama.js"></script>
<script src="slide.js"></script>
</body>
</html>
diaporama.js
class Diaporama {
constructor(src, images) {
this.src = src;
this.images = images;
this.position = 0;
this.start();
}
slideLeft() {
if (this.position <= 0) {
this.position = this.images.length - 1;
} else {
this.position--;
}
this.src = this.images[this.position];
}
slideRight() {
if (this.position > this.length-1) {
this.position = 0;
}
else {
this.position++;
}
this.src = this.images[this.position];
}
start() {
this.src = this.images[this.position];
}
}
slide.js
var images = Array('img/caroussel1.png', 'img/caroussel2.jpg', 'img/caroussel3.jpg', 'img/caroussel4.jpg', 'img/caroussel5.jpg');
var src = document.getElementById("diapo").src;
var diaporama = new Diaporama(src, images);
setInterval(function () { diaporama.slideLeft(); }, 5000);
console.log(src);
At a minimum, it looks like one problem is that:
You have an image element with ID diapo in your HTML, and then in the DOM, which has an empty src attribute.
In slide.js, you attempt to create a new instance of the class Diaporama, called diaporama, using the empty src attribute that you have stored in the variable src in slide.js.
Since an img element needs a src attribute with an actual URL, in order to show the image at that URL, you are seeing nothing, since you have not provided a URL (You won't get an error either, since an empty src attribute is perfectly valid HTML, and causes no JS errors)
UPDATE IN RESPONSE TO COMMENTS
The critical issue (or oversight), is that you have:
a carousel element in the index.html file, which is then represented in the DOM (which is what we expect)
an instance of class Diaporama called diaporama in slide.js, which has no link to the DOM carousel that you want it to have: all diaporama has is a String, taken from the src attribute of the DOM carousel, which refers to the URL path of various images. The diaporama instance can never "reach out" and update the DOM carousel, given the code you have written.
Thankfully, the fix is very simple.
As you know, there needs to be link between the DOM and object that you have created; creating such a link is straight-forward and just involves DOM queries.
I have added a solution (I have placed ALL the JS in one file, rather than two files -- as you have -- but this is not important)
class Diaporama {
constructor(imgElem, images) {
this.imgElem = imgElem;
this.images = images;
this.position = 0;
this.start();
}
slideLeft() {
if (this.position <= 0) {
this.position = this.images.length - 1;
} else {
this.position--;
}
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
slideRight() {
// there was an error in your original "slideRight" method: a typo and an "off-by-error"
if (this.position >= this.images.length-1) {
this.position = 0;
}
else {
this.position++;
}
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
start() {
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
}
// prefer an Array literal rather than call to Array -- less verbose, and slightly faster
var images = ['img/one.jpg', 'img/two.jpg', 'img/three.jpg'];
// This is where 'bridge' between "carousel.js" and the DOM is created: we 'cache' a reference to the carousel 'img' element,
// which we will then modify from within the 'carousel' instance of class Diaporama
var imgElem = window.document.getElementById('carousel').querySelector('img');
var carousel = new Diaporama(imgElem, images);
carousel.start();
// create 'delegated' event listener on document, and trigger correct method of 'carousel' in response to user interaction
window.document.addEventListener('click', ev => {
const target = ev.target;
if(target.id === 'back_button') {
carousel.slideLeft();
} else if(target.id === 'next_button') {
carousel.slideRight();
}
});
.carousel {
max-height: 400px;
max-width: 600px;
background: rgb(250,250,200);
overflow: hidden;
}
.button-wrapper {
display: flex;
justify-content: space-around;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Carousel</title>
</head>
<body>
<h1>Carousel slider (OOP)</h1>
<section id="carousel" class="carousel">
<div class="button-wrapper">
<button id="back_button">Back</button>
<button id="next_button">Next</button>
</div>
<img src="" alt="carousel image">
</section>
<script src="carousel.js"></script>
</body>
</html>
I hope this helps answer your question!
If it does, then please mark my answer as the accepted one.
If you still have questions, then let me know, and I will do my best to answer them.

highlight span tags inside div on onmouseup

I am trying to highlight individual spans inside my document body onmouseup. My trouble is that for some reason every element is highlighted by default and I can't seem to get it to work on window.getSelection(). I only need it to highlight the span when I've clicked it.
Would anyone know a quick way of doing this?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>
<script src="./highlight.js"></script>
</body>
</html>
var documentbody = document.getElementById("docbod");
/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
var divarray = []
var state = ["hey", "there", "how", "are", "you", "doing?"]
for (let i = 0; i < state.length; i++) {
span = document.createElement("span")
span.textContent = state[i]
//-------^
span.id = "word" + i;
span.classList.add("textBackground")
span.addEventListener("onMouseup", highlight(span));
div.append(span);
div.append(" ");
}
}
splitdocintowords(documentbody);
/* highlights a selected word within the document*/
function highlight (element){
element.style.background='yellow';
console.log("selected element")
}
You have a mistake when adding event listener, the name of the event is 'mouseup'.
span.addEventListener("mouseup", () => span.style.background = 'yellow');

Button background color toggle

I have been trying to toggle the background-color property of a button onclick but the color only changes once and does not toggle back and forth. Below is the code.
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.style.backgroundColor == "rgb(244,113,33)") {
property.style.backgroundColor=color;
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
}
}
<input type="button" id="btnHousing" value="Housing" onclick="toggleLayer('transparent1');btnColor('btnHousing','rgb(255,242,0)');" />
A simple solution (JS, CSS and HTML in order).
You setup a class in CSS, then select the button (yes the JS could have been done in one line) and toggle the class.
var button1 = document.querySelector("button");
button1.addEventListener("click", function() {
document.body.classList.toggle("colorred");
});
.colorred {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Change color to background</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<button>Click me!</button>
<script src="main.js"></script>
</body>
</html>
The problem you're having is that the background-color of an element is reported differently in browsers, either rgb, rgba (with, or without, spaces) in hex or in HSL...
So the button will likely never satisfy the if condition, meaning it will always go to the else.
With that in mind, I'd suggest using a class-name to keep track of the un/toggled state:
function btnColor(btn, color) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.style.backgroundColor=color;
property.className = 'toggled'
}
else {
property.style.backgroundColor = "rgb(244,113,33)";
property.className = '';
}
}
JS Fiddle demo.
Of course, if we're using the class of the element, we might as well use CSS to style the element:
function btnColor(btn) {
var property = document.getElementById(btn);
if (property.className !== 'toggled') {
property.className = 'toggled'
}
else {
property.className = '';
}
}
With the CSS:
#btnHousing {
background-color: rgb(255,242,0);
}
#btnHousing.toggled {
background-color: rgb(244,113,33);
}
JS Fiddle demo.
The previous JavaScript could be simplified (using the same CSS) to:
function btnColor(btn) {
var property = document.getElementById(btn);
property.className = 'toggled' == property.className ? '' : 'toggled';
}
JS Fiddle demo.

Categories