Append Style to DOM not Replacing Existing - javascript

How can I append style element to DOM without eliminating existing style on the item (eg color, text-align, etc)?
The event calls the function, but the problem is 'Style' gets completely replaced with the single item instead.
I have simple code triggered on the event:
function changeback(onoff) {
if(onoff) {
document.getElementById("field1").style.background="#fff";
} else
document.getElementById("field1").style.background="#000";
}

Here is how you can do it :
var elem = document.getElementById('YOUR ELEMENT ID');
elem.style.setProperty('border','1px solid black','');
elem.style is an object implementing the CSSStyleDeclaration interface which supports a setProperty function. If you check the style property in Firebug now, you will notice addition of the border property within the style attribute of the element.

Which browser are you using? In Chrome, this works for me:
<html>
<head>
<style type="text/css">
.test { background: #ff0000; font-family: "Verdana"; }
</style>
<script type="text/javascript">
function changeback(onoff)
{
if(onoff){
document.getElementById("field1").style.background="#0f0";
} else {
document.getElementById("field1").style.background="#000";
}
}
</script>
</head>
<body>
<h1>Test</h1>
<p id="field1" onclick="changeback(true);" class="test">This is a test</p>
</body>
</html>
When I click on the text, the background color changes, but the rest of the style (in this case, the font) stays the same.
Is that what you're trying to do?

Related

If statement to check css property not working

I have a div that displays a little popup menu when clicked. I want users to be able to click anywhere in the body of the site to close the popup, but when I add code for that, the popup cant be opened at all anymore.
So I tried adding an if-statement so that the closemenu() function will only try close the popup if its already open, but it seems like the statement is evaluating to false even if the popup is open.
Here is the HTML for showing the popup:
<div class="popcolor" onclick="showmenu()"> Click!
<span class="popupcolor" id="myPopup">Pop!</span>
</div>
Here is the css:
.popcolor .show {
visibility: visible;
-webkit-animation: fadeIn 0.5s;
animation: fadeIn 0.5s;
}
Here is the Javascript:
function showmenu() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.style.visibility == "visible") {
popup.classList.toggle("close");
};
}
Here is the HTML for closing the popup:
<body onclick="closemenu()">
I've been through every post I can find on this for solutions, and I'm still stuck. Any help is appreciated.
You can use the getComputedStyle() method on the window object, to calculate the style rules that result from the classes applied to your popup element.
This gives you a reliable way of determining the values of different styling rules that result from, say, the 'close' class being applied to popup
Something along the lines of this should work for you:
function closemenu() {
var popup = document.getElementById("myPopup");
// Get the computed style, that is the combination of styles
// resulting from your CSS classlist, etc
var computedStyle = window.getComputedStyle(popup, null);
// Get visibility value from computed styles
var visiblityValue = computedStyle.getPropertyValue("visibility")
if (visiblityValue == "visible") {
popup.classList.toggle("show"); // Correct this from "close" to "show"
};
}
There are also some other functional issues with your implementation which are causing problems. Consider updating your showmenu() method to:
function showmenu(event) {
// Prevent event propagation, which would cause closemenu to call
// after this method is called
event.stopPropagation()
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
For more information on getComputedStyle(), see the MDN documentation
Problem here is that click event triggered from div bubbles up to body which eventually closes the popup.
function showmenu(e) {
e.stopPropagation();
console.log('toggle');
document.getElementById("myPopup").classList.toggle("close");
}
function closemenu(e) {
e.stopPropagation();
console.log('hide');
document.getElementById("myPopup").classList.add("close");
}
#myPopup.close {
visibility: hidden;
}
body {
border: 1px solid #ccc;
padding: 2rem;
}
<body onclick="closemenu(event)">
<div class="popcolor" onclick="showmenu(event)"> Click!
<span class="popupcolor close" id="myPopup">Pop!</span>
</div>
</body>
P.S. Use event.stopPropagation() to cancel/consume event
Because the visibility property is being set at the class level, the style information isn't available in the style property of your element. Maybe instead of checking for a specific style, you can check to see if the 'show' class is currently assigned to your element like so:
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.classList.contains("show")) {
popup.classList.toggle("close");
};
}
Problem in your code is with the use of JavaScript functions.
Try this simple example I took from W3Schools and enhanced it for your case.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_add_class
There seems to be some issue with W3CSchool TryIt Editor page. Here is the link to JSBin for the same code: https://jsbin.com/xefolinape/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunctionClose()">Close it</button>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
function myFunctionClose() {
var element = document.getElementById("myDIV");
element.classList.remove("mystyle");
}
</script>
</body>
</html>
Hope this helps!

stuck with onclick tried google couldn't find answer

i need help getting this to work, tried everything google had to offer.. but still stuck. what i need it to do is load the value of (div id="availablecredits") to (div id="beta") on click. can any body help me out?
onclick="javascript:document.getElementById('beta').value=(javascript:document.getElementById('availablecredits').value)"
i also tried onclick="javascript:document.getElementById('beta').value=('#availablecredits')"
The property value is common for input elements like <input>, <select>, <textarea> and <button>
I think what you want is to copy a content of a <div> element to another div. If it's the case, use innerHTML instead of value.
Here is a snippet, just click on the gray area.
#div-two {
min-height: 20px;
background: #CCC;
}
<div id="div-one">
Hello this is #div-one
</div>
<div id="div-two" onclick="document.getElementById('div-two').innerHTML=document.getElementById('div-one').innerHTML"></div>
SNIPPET #2
You've defined a third <div> which you use as trigger but you can't click it if it's not visible, because it's height is 0. Specify some text inside it, then it's visible and the JS part work. Take a look at the snippet.
#getCredits {
background: #CCC;
}
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits" onclick="document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML">Click here to get available credits</div>
SNIPPET #3 - jQuery
$('#getCredits').click(function() {
$("#beta").html($('#availablecredits').html());
});;
#getCredits {
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
Simple javascript function, change the ids in the function call to those of the elements in question.
<script>
function set_value( src,tgt ){
document.getElementById( tgt ).innerHTML=document.getElementById( src ).innerHTML;
}
</script>
<style>.p5{ display:block; padding:1rem; margin:1rem; border:1px solid black;}</style>
<div class='p5' id='src_div' onclick="set_value('src_div','tgt_div')">Weebles wobble but they don't fall down!</div>
<div class='p5' id='tgt_div'></div>
Or you can use a link to set the value
you should try to avoid writing inline event.try this:
<style>
#getCredits {
background: #CCC;
}
</style>
<div id="beta">0.00</div>
<div id="availablecredits">500</div>
<div id="getCredits">Click here to get available credits</div>
<script>
document.getElementById('getCredits').addEventListener("click",function(){
document.getElementById('beta').innerHTML=document.getElementById('availablecredits').innerHTML;
});
</script>
Why inline css and javascript are bad:http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
The .val() method is sometimes useful:
var input = $("#Input").val();

How to change the default highlight color of drop down in html from blue to some other color for <select><option> tag

How to change the default highlight color of drop down in HTML from blue to some other color for <select><option> tags, using some CSS properties or from Javascript?
The requirement is I have to use the <select> <option> tags only. I tried the code below, but it didn't work for me:
<html>
<head>
<title>Dropdown Colour</title>
<style type="text/css">
option:hover {
background:#C6C4BD;
}
</style>
</head>
<body>
<select>
<option>Shell</option>
<option>Cabbage</option>
<option>Beans</option>
<option>Cheese</option>
<option>Clock</option>
<option>Monkey</option>
</select>
</body>
</html>
try setting outline and/or border properties of select.
select{outline:1px solid green;border:1px solid black;}
Currently there is no way I know of that this can be accomplished using only CSS.
However, using jQuery I was able to achieve a similar effect.
Live Demo
Your dropdown changes because i have to set the size of the select element which makes it look like a list-box. Maybe somebody can improvise on this.
Here is the jQuery i used
$(document).ready(function (event) {
$('select').on('mouseenter', 'option', function (e) {
this.style.background = "limegreen";
});
$('select').on('mouseleave', 'option', function (e) {
this.style.background = "none";
});
});
Try to change like this, hope it may help you
select option{
background: red;
color: #fff;
outline:1px solid green;
}

how do you get the specific style altered with a CSS class?

Quick one, not sure if its possible.
How can I get the specific style altered with a CSS class using jQuery/JS.
Example:
html looks like:
<tab>
<a class="anchor">a</a>
</tab>
CSS looks like:
a{border:1px}
.anchor{color:green}
So if i do something like :
$('.anchor').myReturnStyle() and it returns color or an array if there more styles in .anchor
$('.anchor').MyReturnStyleValue('color') returns 'green'
BUT
$('.anchor').returnStyleValue('border') returns false as this is not changed by .anchor Class
You can use jQuery's css(..) method to achieve this. Please note that:
Shorthand CSS properties (e.g. margin, background, border) are not supported.
Here is an example:
<div>
<a class="anchor">a</a>
</div>
<style type="text/css">
a { background-color: #000; }
.anchor{ color: green; }
</style>
<script type="text/javascript">
$(document).ready(function () {
alert($($('.anchor').get(0).nodeName).css('background-color'));
});
</script>
See the jsFiddle demo

How do I give successive CSS classes different colors (Javascript)?

I have annotated text, and I'd like certain annotated words to be color-coded along with their annotations, but I don't want to have to do it manually. Is there a way to have javascript (or jquery) or even css make the first class="Noted" green, then the second blue, and then on the fifth go back to green, and to do the same with the corresponding class="note"s?
you can do this using :nth-child you will need something like jQuery for support for IE though.. working on that...
here's a first fiddle for a CSS only version http:http://jsfiddle.net/zhQ67/2/ ** FIDDLE updated with new code below **
CSS:
.noted:nth-child(4n+1) {
background: green;
}
.noted:nth-child(4n+2) {
background: red;
}
.noted:nth-child(4n+3) {
background: yellow;
}
.noted:nth-child(4n+4) {
background: blue;
}
final update using thirtdots updated code and including some jQuery for IE - JSBIN Page
Ok, based on your jsFiddle you could use something along these lines to get the result you're after:
p:nth-child(5n+1) .Noted, p:nth-child(5n+1) .Annotation {color: green}
as demonstarted in this modification of your jsfiddle
You can get all elements with getElementsByClass an then simply iterate through them, giving every single one and it's corresponding element class="note" a different color.
In jquery.....set the colors as you see fit. jsFiddle demo
<script type="text/javascript">
$(".Noted").each(function(i,e){
switch(i%4){
case 0: $(this).css({color:"#f00"});break;
case 1: $(this).css({color:"#0f0"});break;
case 2: $(this).css({color:"#00f"});break;
case 3: $(this).css({color:"#ff9"});break;
case 4: $(this).css({color:"#f90"});break;
}
});
</script>
First, try encapsulating your elements inside a container. It will make the children selection much easier.
<div id="parent">
<span class="note">Green</span>, <span class="note">blue</span>
then <span class="note">red</span>.
</div>
then, the js :
<script>
var children = document.getElementById('parent').getElementsByTagName('*')
,colours = ['green','blue','red','orange']
,i,j=0,max;
for (i = 0, max = children.length; i<max; i++) {
if(children[i].getAttribute('class') == 'note') {
children[i].setAttribute('style','color:' + colours[j]);
j++;
if (j>colours.length) {
j = 0;
}
}
}
</script>
If the HTML is being generated by a server side script, you could have the script assign a class based on which Annotation is being generated, then in the stylesheet, assign a color to that class, like so:
.note1 { //Corresponds to class='note1'
color: green; //or whatever you want
}
.note2 { //Corresponds to class='note2'
color: blue; //or whatever you want
}
/* and so on */
If the HTML is simply being written statically, then assign the class corresponding to how it defined in the stylesheet, depending on the color you want.
If they are children, you could use something along the lines of clairesuzy's solution.
The other option is to assign all of them as class note and then have an javascript that colors everything marked as class note based on a predefined order that you set.
That would probably be along the lines of something like this (using jQuery):
Demo here: http://jsfiddle.net/hs8Nm/
<p class="note">Note 1</p>
<p class="note">Note 2</p>
<p class="note">Note 3</p>
<p class="note">Note 4</p>
and the corresponding Javascript:
$(document).ready(function(){
var colors = ['green','blue','orange','yellow',"FFFFF0"]; //Assign your color order here.
$('.note').each(function(index){
this.css('color',colors[index%5]);
});
});
Yes, it can be done using CSS Selectors. You can get the first, second, third, and so on element in a list of matching occurences.
Here you go:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<title>Cycle classes</title>
<style>
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
</style>
<script>
$(document).ready( function() {
$(".Noted").each(function(i) {
var classes = ['green','blue','yellow'];
$(this).addClass(classes[i % classes.length])
});
})
</script>
</head>
<body>
<div class="Noted">hello</div>
<div class="Noted">world</div>
<div class="Noted">it works</div>
</body>
</html>

Categories