Updating CSS gradient using JS [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 days ago.
Improve this question
Please explain proper way to update a calculated style i.e. set in a CSS doc. document.body.style.background will take a color but not take a gradient. Example follows:
<button onclick="myFunction()">Set background</button>
<script>
function myFunction() {
foo = "#fedcba";
faa = "linear-gradient(45deg, #abcdef, #fedcba);";
document.body.style.background = faa; //foo works, faa doesn't work
}
</script>
I've tried many different iterations of the document.body.style.background and have read where some selectors are read only while others can be manipulated.
My present code: with comments added
Style from CSS file:
body {
background-color: #fedcba;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
font-family: sans-serif;
font-size: 1.2em;
background: -webkit-linear-gradient(315deg, #fedcba, #444);
background: -moz-linear-gradient(315deg, #fedcba, #444);
background: -o-linear-gradient(315deg, #fedcba, #444);
background: -ms-linear-gradient(315deg, #fedcba, #444);
background: linear-gradient(135deg, rgba(10, 100, 0, 100), rgba(200, 200, 200, 100));
background-repeat: no-repeat;
background-attachment: fixed;
}
function setGradient() {
const style = getComputedStyle(body); // reads the CSS for the body style
const background = style.background; //selects the background style
console.info("background: ", background); //writes the style to the console for trouble shooting
var prefix = getCssValuePrefix(); //gets browser prefix -o-, -moz-, -webkit-, -ms-
var orentation = slider; // a number from 0 to 360
var something = prefix + "linear-gradient(" + orentation + "deg, " + color1 + ", " + color2 +")";
//builds a string for the background :: here I have also tried color1.value and color2.value
console.info("setGradient before: ", something); //displays the gradient before being set
document.body.style.background = something; // should set the background to the new gradient
console.info("setGradient after: ", something); //shows that the variables are null
}
// the console returns: setGradient before: -webkit-linear-gradient(nulldeg, null, null)
//Pick and set Bkground colors and orentation
color1.addEventListener("color1", setGradient); //color1 from colorpicker input
color2.addEventListener("color2", setGradient); //color2 from colorpicker input
slider.oninput = setGradient(); //a number from 0-360 step 1 value 180

It's just a small typo. You need to remove the ; to make it a valid CSS value.
<button onclick="myFunction()">Set background</button>
<script>
function myFunction() {
let faa = "linear-gradient(45deg, #abcdef, #fedcba)";
document.body.style.background = faa;
}
</script>

Related

How to change css class property after X button is clicked to transparent [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Can you show me Javascript that allows you to change the background color of the page to another color. For example, I have a blue background color and I want to change it to green. The color must be changed when the user presses a button that triggers the event.
I saw that it exists on many sites but I could not write the code
I write in REACTJS I would love to have your help
Thanks...
If you want change background color on button click, you should use JavaScript function and change a style in the HTML page.
function chBackcolor(color) {
document.body.style.background = color;
}
It is a function in JavaScript for change color, and you will be call this function in your event, for example :
<input type="button" onclick="chBackcolor('red');">
I recommend to use jQuery for this.
If you want it only for some seconds, you can use setTimeout function:
window.setTimeout("chBackColor()",10000);
You can set the background color of an object using CSS.
You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.
body {
background-color: blue;
}
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
I'm suggest that you learn about Jquery, most popular JS library.
With jquery it's simple to acomplish what you want.Simle example below:
$(“#DIV_YOU_WANT_CHANGE”).click(function() {
$(this).addClass(“.your_class_with_new_color”);
});
Here you can find solutions for both your problems.
document.body.style.height = '500px';
document.body.addEventListener('click', function(e){
var self = this,
old_bg = this.style.background;
this.style.background = this.style.background=='green'? 'blue':'green';
setTimeout(function(){
self.style.background = old_bg;
}, 1000);
})
http://jsfiddle.net/ea1xf3sx/
You can sets the body's background colour using document.body.style.backgroundColor = "red"; so this can be put into a function that's called when the user clicks.
The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red"; window.setTimeout("yourFunction()",10000); which calls yourFunction in 10 seconds to change the colour back.
You can use setTimeout():
var addBg = function(e) {
e = e || window.event;
e.preventDefault();
var el = e.target || e.srcElement;
el.className = 'bg';
setTimeout(function() {
removeBg(el);
}, 10 * 1000); //<-- (in miliseconds)
};
var removeBg = function(el) {
el.className = '';
};
div {
border: 1px solid grey;
padding: 5px 7px;
display: inline-block;
margin: 5px;
}
.bg {
background: orange;
}
<body onclick='addBg(event);'>This is body
<br/>
<div onclick='addBg(event);'>This is div
</div>
</body>
Using jQuery:
var addBg = function(e) {
e.stopPropagation();
var el = $(this);
el.addClass('bg');
setTimeout(function() {
removeBg(el);
}, 10 * 1000); //<-- (in miliseconds)
};
var removeBg = function(el) {
$(el).removeClass('bg');
};
$(function() {
$('body, div').on('click', addBg);
});
div {
border: 1px solid grey;
padding: 5px 7px;
display: inline-block;
margin: 5px;
}
.bg {
background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>This is body
<br/>
<div>This is div</div>
</body>
you can do this---
<input type="button" onClick="changebackColor">
//changes background color to black on click
function changebackColor(){
document.body.style.backgroundColor = "black";
document.getElementById("divID").style.backgroundColor = "black";
window.setTimeout("yourFunction()",10000);
}

If statement inside a JavaScript game not correctly executing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have the following code and am trying to get the flappy bird to rise in the air which any part of the canvas is clicked.
I think I have placed the if statement wrong or there is some error with it.
if(c.onclick="True"){
birdDY==9;
}
Could the error in this code be pointed out along with an explanation for where it should go?
Whole code:
<style>
#block{
width: 50px;
height: 500px;
background-color: greenyellow;
position: relative;
left: 400px;
animation: block 2s infinite linear;
}
#keyframes block{
0%{left:400px}
100%{left:-50px}
}
#hole{
width: 50px;
height: 150px;
background-color: white;
position: relative;
left: 400px;
top: -500px;
animation: block 2s infinite linear;
}
</style>
<body style="height: 100vh; background: #111; text-align: center;">
<canvas id="c" width="400" height="400"></canvas>
<div id="block"></div>
<script>
//set up context
context = c.getContext("2d");
//create bird
const bird = new Image();
bird.src = "bird.png";
//create variables
var canvasSize = 400;
var birdSize=30;
var birdX = 0;
var birdY =200;
var birdDY = 0;
var score = 0;
var bestScore=0;
var interval = 30; //the speed at which the game is played
c.onclick = () => (birdDY = 9) ;
setInterval(() => {
context.fillStyle = "skyblue";
context.fillRect(0,0,canvasSize,canvasSize); // Draw sky
birdY -= birdDY -= 0.5; // Gravity
context.drawImage(bird, birdX, birdY, birdSize, birdSize); // Draw bird (multiply the birdSize by a number to adjust size)
context.fillStyle = "black";
context.fillText(`Flappy Birds`, 170, 10); //x and y
context.fillText(`Score: ${score++}`,350, 380); // Draw score
context.fillStyle = "green";
context.fillRect(300,20,canvasSize,canvasSize); // Draw blocks
}, interval)
</script>
</body>
You're not approaching the problem correctly.
First, = is used to assign a value, not test it. To *compare values, use == or ===. In your case, you are setting onclick to "True", which itself can be evaluated as a "truthy" statement, so you would always execute the true branch of the if.
Next, in JavaScript, true is how you reference the Boolean true value. "True" is a string.
But, onclick is a property and you shouldn't be testing it for true in the first place. Your code is set to run immediately, instead you should be setting up an "event handling function (event handler) that will run when the element gets clicked. To do this use, .addEventListener() as in the following
// Get a reference to the DOM element
const button = document.querySelector("button");
// Set up the event handler
button.addEventListener("click", doStuff);
// Define the event handling callback function
function doStuff(event){
console.log("You clicked the button.");
}
<button>Click Me</button>
In your case, that would mean your code would look like:
c.addEventLIstener("click", function(){
birdDY = 9; }
);
try
if(c.onclick=="True"){
birdDY=9;
}
// or try
if(c.onclick===true){
birdDY=9;
}
Reference
https://www.w3schools.com/js/js_if_else.asp
Which equals operator (== vs ===) should be used in JavaScript comparisons?

Javascript - Function to change element colour but first call never works [duplicate]

This question already has answers here:
Javascript styling toggle doesn't work first click
(4 answers)
Closed 5 years ago.
I have a simple function written in JS that when called, will check the current background colour of the element. If it is a certain colour then it will change to a different and if it is a another colour then it will change back to the first colour - like a toggle.
The only problem I have is that the first call of the function never work but I can't work out why. Even though I am expecting it to turn blue?
function changeBgColor() {
var x = document.getElementById(dest_1);
var dest_bgColor = x.style.backgroundColor;
if (dest_bgColor === "aquamarine") {
x.style.backgroundColor = "blue";
} else {
x.style.backgroundColor = "aquamarine";
}
return;
}
.selectBox {
display: block;
width: 100px;
height: 100px;
background-color: aquamarine;
}
A
While the browser is rendering the element using the color from your style rule, the rule won't set the element's style.backgroundColor. It's a bad idea in general to rely on values in these properties, you should always keep/switch a separate variable, then only set style.x.
To find out the actual value, you can use getComputedStyle(x).backgroundColor. In your example, this returns rgb(127, 255, 212) though, not aquamarine.
var cols = ["aquamarine", "blue"];
var index = 0;
function changeBgColor() {
var x = document.getElementById("dest_1");
// move to next color
index = (index + 1) % cols.length;
x.style.backgroundColor = cols[index];
return;
}
.selectBox {
display: block;
width: 100px;
height: 100px;
background-color: aquamarine;
}
A

How do I achieve this animation using javascript/jquery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have been searching how to accomplish the animation on this website using html/css/js/jquery: https://www.nobledesktop.com/certificates/web-design. In particular, I want to know how to achieve the highlighting then deleting effect of the animation, but I also want to know how to insert the next word one character at a time with a delay. This question has been asked before but did not achieve the last specification that I have mentioned above.
This is the thread I am referring to: Web animation css highlight
This is an image of the animation I'm talking about on http://www.nobledesktop.com/certificates/web-design.
http://pasteboard.co/2ywHhxGE.png
I have looked at the source code related to that span but I have no clue where to start past highlighting the text as answered in the aforementioned thread. Any help would be appreciated. Thanks!
I know it's a bit late and the jquery.typer.js library will probably be the best solution as explained by Marcos, but I have time on my hands right now and I tried to clone the behaviour from the link you are referring to with jQuery and CSS.
Here is my working demo.
I created recursive functions for the typing animation and word traversal, in tandem with CSS transitions for the highlight animation:
JS
function typify($elem, wordSec, charSec, highlightSec) {
var texts = $elem.data('type').split(',');
$elem.css({
transition: 'background-size ' + (highlightSec / 1000) + 's'
});
addByWord($elem, texts, 0, wordSec, charSec, highlightSec);
}
function addByWord($elem, texts, i, wordSec, charSec, highlightSec) {
if (i < texts.length) {
var text = texts[i],
duration = (text.length * charSec);
$elem.text('')
.addClass('reset')
.removeClass('highlight');
addByLetter($elem, texts[i], 0, charSec);
setTimeout(function () {
$elem.removeClass('reset')
.addClass('highlight');
}, duration + wordSec);
setTimeout(function () {
addByWord($elem, texts, ++i, wordSec, charSec, highlightSec);
}, duration + highlightSec + 300 + wordSec);
} else {
addByWord($elem, texts, 0, wordSec, charSec, highlightSec);
}
}
function addByLetter($elem, txt, i, sec) {
if (i < txt.length) {
var ch = txt.split('')[i];
$elem.text($elem.text() + ch);
setTimeout(function () {
addByLetter($elem, txt, ++i, sec);
}, sec);
}
}
typify($('.animation'), 1500, 105, 300);
CSS
.animation {
padding-bottom: 5px;
border-bottom: 5px solid #00a8e6;
box-sizing: content-box;
display: inline-block;
background: linear-gradient(to left, rgba(0, 20, 255, 0.5) 0%, rgba(0, 20, 255, 0.5) 100%) no-repeat top right;
background-size: 0% 100%;
}
.animation.highlight {
background-size: 100% 100%;
}
.animation.reset {
background: transparent;
background-size: 0% 100%;
}
The definition of parameters of the function, typify($elem, wordSec, charSec, highlightSec) below:
$elem - jQuery element you want to target (should have data-type with
values separated by strings.
wordSec - duration of each word to be shown on screen in milliseconds,
after being typed and before being highlighted
charSec - speed of typing animation per letter milliseconds
highlightSec - speed of CSS highlight animation in milliseconds
They accomplished it by using the jquery.typer.js library. You can take a look at that source and see how it's done.
But in the website you pointed, they have modified the plugin slightly. For instance, they added an option called highlightEverything, to avoid the default behavior of selecting only the text that changes between transitions.

Html Country List with flags [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I am looking for a way to select and display a list of countries, preferably with flags. Any suggestions?
I started of by trying this jQuery plugin http://www.graphicpush.com/website-language-dropdown-with-jquery, but as the list of countries I have is quite large it turned out that the performance was really bad (too many http requests to images). Also the list is bulky when it is larger than 50 elements.
Just wanted to suggest a (imho) smarter way of doing the flags sprite.
The idea is to save the flags in a grid according to the country iso2 code.
1st letter -> vertical position
2nd letter -> horizontal position
Examples (for 16x11px flags + 4x4px spacing):
Austria = AT
A = 1 => vertically 1st row => y = (1-1)*(11+4) = 0
T = 20 => horizontally 20th column => x = (20-1)*(16+4) = 380
United States = US
U = 21 => vertically 21st row => y = (21-1)*(11+4) = 300
S = 19 => horizontally 19th column => x = (19-1)*(16+4) = 360
This way I can calculate the flag location with a very easy function on the client side without the need of 200+ extra style definitions.
Sample jQuery plugin:
(function($) {
// size = flag size + spacing
var default_size = {
w: 20,
h: 15
};
function calcPos(letter, size) {
return -(letter.toLowerCase().charCodeAt(0) - 97) * size;
}
$.fn.setFlagPosition = function(iso, size) {
size || (size = default_size);
return $(this).css('background-position',
[calcPos(iso[1], size.w), 'px ', calcPos(iso[0], size.h), 'px'].join(''));
};
})(jQuery);
Demo Usage:
$('.country i').setFlagPosition('es');
http://jsfiddle.net/roberkules/TxAhb/
And here my flag sprite:
Note from the future: jQuery UI autocomplete now supports custom
rendering by default, see
http://api.jqueryui.com/autocomplete/#method-_renderItem.
It's pretty easy. Things you need:
jQuery UI auto-complete
UI auto-complete html extension
A list of country names/codes
A CSS sprite with all flags
Remember, Google is your friend. Blend the ingredients well, carefully whisk some javascript in, and it's done - in 7 lines of code:
var countries = [["Argentina", "ar"], ...];
var countryNames = countries.map(function(country){
return {
label: '<div class="flag '+country[1].toLowerCase()+'">'+country[0]+'</div>',
value: country[0]
}
});
$('#country').autocomplete({
source: countryNames,
html: true
});
Here's this code in action
As mentioned by commenters, a CSS sprite is the proper solution here. Fortunately, there are many CSS sprites of flags freely available. This one looks pretty good.
We will have to tweak the dropdown code to accomodate that pre-made CSS sprite. I've gone ahead and done that for you. Here's a live demo.
languageswitcher.js
## -44,10 +44,11 ##
source.removeAttr("autocomplete");
var selected = source.find("option:selected");
var options = $("option", source);
- $("#country-select").append('<dl id="target" class="dropdown"></dl>')
- $("#target").append('<dt class="' + selected.val() + '"><span class="flag"></span><em>' + selected.text() + '</em></dt>')
- $("#target").append('<dd><ul></ul></dd>')
+ $("#country-select").append('<dl id="target" class="dropdown f16"></dl>')
+ $("#target").append('<dt><em class="flag ' + selected.val().toLowerCase() + '">' + selected.text() + '</em></dt>');
+ $("#target").append('<dd><ul></ul></dd>');
+ var $drop = $("#target dd ul");
options.each(function(){
- $("#target dd ul").append('<li class="' + $(this).val() + '"><span class="flag"></span><em>' + $(this).text() + '</em></li>');
+ $drop.append('<li><em class="flag ' + $(this).val().toLowerCase() + '">' + $(this).text() + '</em></li>');
});
}
languageswitcher.css
## -45,6 +45,8 ##
.dropdown dd { position: relative; }
+.dropdown ul { max-height:350px; overflow-y:auto; overflow-x:hidden; }
+
.dropdown a {
text-decoration: none;
outline: 0;
## -52,6 +54,7 ##
display: block;
width: 130px;
overflow: hidden;
+ white-space:nowrap;
}
.dropdown dt a {
## -107,23 +110,6 ##
padding: 2px 10px;
}
- .dropdown dd ul li a span,
- .dropdown dt a span {
- float: left;
- width: 16px;
- height: 11px;
- margin: 2px 6px 0 0;
- background-image: url(flags.png);
- background-repeat: no-repeat;
- cursor: pointer;
- }
-
- .us a span { background-position: 0 0 }
- .uk a span { background-position: -16px 0 }
- .fr a span { background-position: -32px 0 }
- .de a span { background-position: -48px 0 }
- .nl a span { background-position: -64px 0 }
-
.dropdown dd ul li a em,
.dropdown dt a em {
font-style: normal;
## -138,3 +124,5 ##
.dropdown dd ul li a:hover { background-color: rgba(255,255,255,.1); }
.dropdown dd ul li a:hover em { color: #fff; }
+
+.flag { padding-left:18px; }
The CSS changes I made were Q&D hacks; you'll probably want to spend some time polishing them. I removed all of the flag-specific stuff from languageswitcher.css since we're using flag16.css.
Also, if the country code doesn't exist in the CSS sprite, the flag shown will default to the
African Union's flag since it is the first image in the sprite. In the demo, several of the countries in my example list don't have a sprite image. Watch out for that.
Here's a file with the list of countries and links to their flags (some of the links might not be working though but most of them are)
Excel File
You can also use flags from http://www.famfamfam.com/lab/icons/flags/ and simply use CSS for positioning the appropriate flag.
----EDITED----
If i need to show flag of my country then i would do mapping from CSS like
<span class='np'></span>
.np {
background: url(./flags_preview_large.png) -172px -397px no-repeat;
width: 14px;
height: 20px;
}

Categories

Resources