How to style the active element using javascript [duplicate] - javascript

This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 6 years ago.
I can use CSS to style an element so that it changes appearance when active. For instance:
.test:active {
background-color: yellow;
}
But how do I do this in javascript if I want to apply it to a specific element, not by class? I can set the background color for the default state using:
document.getElementById("myid").style.backgroundColor = "yellow"
But I can't do this:
document.getElementById("myid").style.active.backgroundColor = "yellow"
I don't want the javascript to respond to the element being active or not - I want to do a static initialization in javascript that then makes a specific element have a different color when it is active.
If the element was guaranteed to have an id I could use javascript to append a style sheet rule which used the #id selector, but I don't have this guarantee. All I can be sure of is I will get a reference to an element and I need to style it so that it has a different color when active.

You could use event listeners with the specific element.
When defining element, try this. You can of course make it a button or whatever:
<!-- in this case, using 'this' will refer to the element at hand. this way the element is targeted even if it has no ID or class -->
<input onfocus="elemFocused(this)" onblur="elemBlurred(this)">
This makes it so that when you focus the element (make it active), it runs the focused function. When it blurs (you select a different input or something), it runs the blurred function. In javascript:
function elemFocused(element){
element.style.backgroundColor = 'yellow'; // sets BG color to yellow
}
function elemBlurred(element){
element.style.backgroundColor = 'initial';// sets BG color to default; you can change if needed
}

I'm not certain that you have programatic access to the ':active' style directly, but you do have access to the active event so you can replicate it with something like this:
In your CSS add a css class to handle your active state, something like:
.active{
background-color: red;
}
Then just add the class on that event:
document.getElementById("myid").onfocus = function(){
this.className += "active";
};
document.getElementById("myid").onblur = function(){
this.className = "/*replace this with the original classes*/";
};

Related

Why doesn't CSS properties work properly with Javascript?

So:
I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
Then I tried to add something in Javascript that would just add <style> </style> element to <head> </head>, but according to a console error the <head> </head> element does not exist, although checking the information about the page this item exists.
Then I just tried to change the properties of these classes in a separate CSS file, but it had no effect.
That's why I'm here. I'm a Javascript beginner and have no idea how to change the background color so that the browser will say it's worth showing.
if (val.read === true) {
div.setAttribute('class', 'readtrue')
} else {
div.setAttribute('class', 'readfalse')
}
val is an object with the 'read' attribute and depending on whether 'read' is true or false, div class should change.
I am not sure how you are getting the variable div but a simple example for what you want to achieve is as follows.
I have commented the code, if you need more clarity, kindly comment on this answer.
function toggleBackgroundColors() {
// Fetch all the elements which has 'element' as a class
var spans = document.getElementsByClassName("element");
// Loop through all the fetched elements
for(var i =0 ; i < spans.length;i++) {
var element = spans[i]; // assign a single element
// Check if the element already has a 'bgColor' class
if(element.className.includes("bgColor","")) {
// If it does, simply remove it
element.className = element.className.replace("bgColor","");
}
else {
// If it does not, simply add it
element.className += " bgColor";
}
}
}
/* basic styling for the element */
.element {
width:20px;
height:20px;
display:inline-block;
border:1px solid #000;
background-color:blue;
}
/* color class you want to add */
.bgColor {
background-color:red;
}
<div>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
<span class="element"></span>
</div>
<button onclick="toggleBackgroundColors()">toggle color</button>
I just tried to use loops to add a background color and a border to each element in class .readtrue or .readfalse, but then somehow the last element, even though it changed class like the others, did not change the border or background color.
It's possible you have another styling overriding your class's style on the last element. Bootstrap and css pseudo-classes like :hover are the usual culprits. Use your browser developer tools and append your class's style with !important, like so background-color: yourColor !important; to test it out.
You could also be adding both classes
Then I tried to add something in Javascript that would just add element to , but according to a console error the element does not exist, although checking the information about the page this item exists.
The correct way to query an element by tag name is document.querySelector("head") or $("head") in jQuery, but jQuery returns a jQuery Object so you dereference it by doing [0]
BUT
Using JavaScript to append a <style> element to the <head> section of your page is horrible practice. Please just add the styling through a reference to a style sheet on the actual HTML.

Passing an element with its applied styles using DOM Manipulation

The goal here is to pass an element (one that is specifically being clicked on) using DOM Manipulation I wanted the svg element to appear with it's all it's applied styles. As of right now, the svg appears without any styling.
I'm thinking there's a way you can pass the clicked element with all of its stylings using this.getAttribute or this.content but those methods come back as undefined, which is why I currently use this.innerHtml (that at least gets clicked element and I can use DOM Manipulation with it).
added eventListeners to each svg element, paired with a function. this.innerHTML seemed to have worked (just the element and none of it's styling).
svg.addEventListener('click', function)
in the function below I used .content and getAttribute where it returned undefined
function () {
var clickedSVG = this.innerHTML
document.getElementById('container2').innerHTML = clickedSVG```
If you want to apply styles to an element on a click event you are going to want to add a class to the element using the classList property. Below is an example where you toggle an elements color on a click event.
First you create the HTML element you would like to toggle and give it an ID along with its default class:
<svg id="icon" class="not-clicked"></svg>
Then you create two CSS classes, one for the default stylings and another for the stylings to be applied on the click event:
.not-clicked {
background-color: black;
}
.clicked {
background-color: red;
}
Then you create a javascript function where you define what you want to happen to your element on the click event, and then call that function with an event listener:
function changeColor(el) {
if (el.classList.contains('not-clicked')) {
el.classList.add('clicked');
el.classList.remove('not-clicked')
} else {
el.classList.add('not-clicked');
el.classList.remove('clicked')
}
}
document.getElementById('icon').addEventListener('click', (e) => {
changeColor(e.target)
});

Applying CSS style to a button in Javascript

I need to apply CSS style defined in main.css to a button from a handler class
In JavaScript, I am hiding/displaying a button using
eventContext.setDisplay(true/false)
I need to apply CSS style to that button when setDisplay is set to true.
The button is visible but not having required style.
app.xml
<button id="btn1" label="Done">
<eventHandlers id="btn1_eventHandlers">
<eventHandler class="custom.handlers.MyHandler" event="render" id="button1_eventHandlers_render_commitEntry" method="done"/>
</eventHandlers>
</button>
done method is defined in MyHandler.js
done: function(eventContext) {
if (count==10)
{
eventContext.setDisplay(true);
}
}
The button gets displayed on the device. Is there any way to apply CSS style to this button at this point so that it can be displayed in intended format?
Simple:
document.getElementByID('yourThing').style.property = 'whatever';
More info here: http://www.w3schools.com/js/js_htmldom_css.asp
If you already have a class containing the button's style, just select your button and add this css class to it
document.getElementById("button1_eventHandlers_render_commitEntry").className = "your_class_name";
If you don't have a css file containing this class, you can apply the style this way.
Select your element and use the style property, and set your css formatting.
document.getElementById("elementId").style.color = "red";
// To use properties with two words like "background-color" use this format "backgroundColor"

How to set link visited color in JQuery

How do I set the visited color of an "a" tag. here is the code I have
theobj.find('a:visited').css('color', thejson.WidgetInfo.TextColor);
The above code is not working. I can only use inline css. Is there a way to do this?
You could construct a style tag, and then write it to the page.
var visited_link_styling = "<style> a:visited{ color:'red'; } </style>";
$('head').append( visited_link_styling );
This might get a little frustrating because JavaScript isn't good at multiline strings.
There isn't a visited selector in jQuery that I am aware, but a similar question points to a plugin to handle this Remy Sharp Visited Plugin
I would suggest you to have a css class and set that class instead but since you can only use inline style you can try this
theobj.find('a').attr("style", "color:#000000 !important");
You can't actually set any properties on an element that only apply to some pseudoselector like visited. CSS documents are declarative, in that you include the CSS in your document and then the set of rules becomes available. JavaScript is not declarative, but executed, which means you can only catch some event and then respond to that. In other words; you can select all the links that are visited and set the color for each, but you can't set the color for visited links.
Now, in order to achieve what you want, you can set a 'live' event handler for the click event on each anchor and then apply the CSS accordingly.
Out of curiosity; why don't you just set the rule in a style element or in a css document?
Is there a reason you are wanting to use jQuery and not pure CSS? Should visited links behave differently than unvisited links?
Depending on your answers to the above questions, the solutions will vary.
CSS:
a:hover { color: #000; }
jQuery (for multiple link color attributes):
var ele = $("#widget a"); // Replace the desired element/object here
var eleColor = ele.css('color'); // Grab what the element's color is
if(eleColor != '#000000' || eleColor != '#000'){ // If it doesn't match X or Y
ele.css("color","000"); // Set to default color
}
^Substituting desired colors above.
Or approach 2:
$("#widget a").css("color","000"); // Set all links to #000
Or approach 3:
$("#widget a").click(function(){ $(this).css("color","000"); });
Working example: http://jsfiddle.net/9N5Xe/

How to change css properties of html elements using javascript or jquery

How can I change CSS from javascript.
I'm using jQuery-ui Dialog and I want to change the style of a DIV from javascript.
Thanks
Check out the jQuery documentation. If you want anything it will be there.
Anyhow, if you want to add styles to elements, you need to use the css function, which has a few variants.
$(selector).css(properties); // option 1
$(selector).css(name, value); // option 2
So if you have a DIV with ID of "mydiv" and you want to make the background red, you would do
$("div#mydiv").css({'background-color' : 'red'}); // option 1
$("div#mydiv").css('background-color','red'); // option 2
The first way is easier if you're setting multiple things at once.
If you want to check what a property is currently set to, you would use a variant of the 2nd option, just omit the value.
var color = $("div#mydiv").css('background-color');
Would make the var color be red if you already set it above, for example.
You can also add and remove classes, doing something like
$(selector).addClass(class_name);
$(selector).removeClass(class_name);
This answer works even without jQuery.
So you have something like this:
<style type="text/css">
.foo { color: Red; }
.bar { color: Blue; }
</style>
<div class="foo" id="redtext"> some red text here </div>
If you wish to change just some attributes, you can always find the element using
var div = document.getElementById('redtext');
function and then change the attached color style by
div.style.color = 'Green';
Making your red text appear in green instead.
If you want to change the class defined for the div to another style class, you can do:
div.className = 'bar';
making the div now use class bar, which makes your previously green text blue.
There are a couple of ways to manipulate elements styles using the jQuery framework. Take a look through the documentation related to CSS and changing attributes:
http://docs.jquery.com/Attributes/addClass#class
http://docs.jquery.com/CSS
Try this.This is jquery code.
$("myDiv").css({"color":"red","display":"block"})
If you are using vanila javacript,try this.
var myDiv = document,getElementById("myDiv");
myDiv.style.display = "block";
myDiv.style.color = "red";

Categories

Resources