How to temporarily modify the CSS of an element - javascript

I am adding a CSS rule to an element with jQuery. E.g. $('#any-el').css('outline', '1px solid red').
I later remove the style with $('#any-el').css('outline', '').
I don't want to disturb any other styles this element may have, and I've found that this method works well for CSS added with external or inline stylesheets, but it will (obviously) modify and then remove any 'outline' given added via JavaScript at any previous point.
What is the best way to ensure that the value of the 'outline' style attribute is restored to the way it was before I modified it?
Here is the whole relevant part of the code:
var last_el = null
$('#mask').mousemove(function(e) {
var mask = $(this).detach()
var el = window.document.elementFromPoint(e.clientX, e.clientY)
if (el != last_el) {
if (last_el) {
$(last_el).css('outline', '')
}
if (el) {
$(el).css('outline', '1px solid red')
}
last_el = el
}
$('body').append(mask)
})
(Basically the #mask overlays the whole page and I outline the element which the mouse is hovering over, underneath the mask.)

You could store the value of the previous outline style in a variable before changing it, and then later restore the value of the variable. E.g.
var last_el = null;
var outline_style = null;
$('#mask').mousemove(function(e) {
var mask = $(this).detach();
var el = window.document.elementFromPoint(e.clientX, e.clientY);
if (el != last_el) {
if (last_el) {
$(last_el).css('outline', outline_style);
}
if (el) {
outline_style = $(el).css('outline');
$(el).css('outline', '1px solid red');
}
last_el = el;
}
$('body').append(mask);
});

The simplest thing you could do to add styles and restore them without any disturbance would be to put your new styles in a class and add/remove that class rather than setting inline styles. Make sure that all styles within the class are made !important.
var $span = $('span');
$('button').click(function () {
var $this = $(this),
override = $this.text() === 'Override';
$span.toggleClass('outline-override');
$this.text(override? 'Restore' : 'Override');
});
.outline-override {
outline: 1px solid red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="outline: 1px solid black;">test</span>
<button>Override</button>

Related

To make the effect work separately for each class (Javascript)

There are three classes named "main-menu."
I want to apply the effect that underlines when I raise the mouse cursor in the area corresponding to each class.
I know that the current target is in the 0th index of the class and I have to use variables, but I don't know how to change that to suit the situation.
I would appreciate it if you could tell me how to solve this problem.
window.onload = function(){
var target = document.getElementsByClassName("main-menu")[0];
target.addEventListener('mouseover', function(){
target.style.borderBottom = "5px solid black";
});
target.addEventListener('mouseout', function(){
target.style.borderBottom = "none";
});
}
Try adding mouse hover css instead
.main-menu:hover {
border-bottom: 5px solid black;
}
You can use loop and add effect to each element. You can do this with css as well
.main-menu:hover { border-bottom: 5px solid black; }
window.onload = function(){
var elements = document.getElementsByClassName("main-menu");
for(let index=0; index < elements.length;index++) {
const target = elements[index];
target.addEventListener('mouseover', function(){
target.style.borderBottom = "5px solid black";
});
target.addEventListener('mouseout', function(){
target.style.borderBottom = "none";
});
})
}

Removing JavaScript behavior

I need to remove the JavaScript behavior that I set on a div.
First, I set the CSS (it's an simple example) :
#redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
#redBloc:hover {
background-color: #3270ad;
}
Okay, for some reasons I need to override the behavior when the mouse is over my div.
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
It works like I want.
But later in my process, I need to reset the JavaScript behavior, to retrieve the behavior written in my CSS file.
How can I do this ?
Thank you
EDIT
I didn't need to override the behavior on the onmouseleave event, but later in my code, by the press of a button "disable behavior" for example.
That was solved by the solution of #T.J.Crowder.
Thank you all !
I think you mean you want to remove the specific background color so that the one from CSS can show through again (rather than "behavior").
If so, assign "" to it:
theElement.style.backgroundColor = "";
If you really do mean behavior and you don't want that mouseover handler to fire anymore, since you've used onmouseover to assign it, you can remove it by assigning null:
theElement.onmouseover = null;
Make your element null on mouseout, like:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseout = function() {
this.style.backgroundColor = '';
};
Have a look at the snippet below:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseout = function() {
this.style.backgroundColor = '';
};
#redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
#redBloc:hover {
background-color: #3270ad;
}
<div id="redBloc"></div>
Hope this helps!
You can remove the effect when user leaves your element using onmouseleave & null the style attribute:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseleave = function() {
this.style.backgroundColor = "";
};
<span id="redBloc">Hover me & leave me!</span>
You need to remove the style attribute by running the this code
var redBloc = document.getElementById('redBloc');
redBloc.removeAttribute('style')
You can have functionality on onmouseleave
redBloc.onmouseleave = function(){
this.removeAttribute('style');
}
You want to give redBloc the style with id #redBloc defined in Your css ... What You can do is create a css class and put all the styles in it that you want to apply on redBloc
.redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
then in your javascript you can add this class to redBloc on mouseover
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.className += " redBloc";
};
and this will add those styles defined in redBloc css class on your redBloc div. Hope this helps !

javascript .style property of span tag in anchor tag not working as expected

I am trying to style some buttons for my website
This is my html
<div>
<a class="page_numbers"><span>100</span></a>
<a class="page_numbers"><span>2</a></span></div>
this is my css
.page_numbers{
display:table-cell;
border:solid;
padding:0px;
border-radius:100px;
width:50px;
height:50px;
text-align:center;
vertical-align:middle;
}
div {
display:table;
border-spacing:10px;
}
}
and finally this is my javascript
var obj=document.getElementsByClassName("page_numbers")
for (i in obj){
console.log(obj[i].children)
obj[i].children[0].style.color="black"
obj[i].style.borderColor="rgb(85,170,255)"
function jun(i){
obj[i].addEventListener('mouseenter',function(){obj[i].style.background="yellow";obj[i].style.color="red"},true)
//
obj[i].addEventListener('mouseleave',function(){
obj[i].style.background="white";
obj[i].style.color="rgb(12,31,22)";},true)
}
jun(i);
}
the background color changes on mouseleave and enter but not the font color...I suppose I am doing something wrong along the way or I am missing a fundamental concept
this is my jsfiddle link
http://jsfiddle.net/repzeroworld/boqv8hak/
advice please..still learning JS
Firstly, all of this should be in CSS and is trivial to do so
.page_numbers:hover
{
background-color: yellow;
}
.page_numbers:hover span
{
color: red;
}
Now the issue you are having is that on about the 4th line of your JS you explicitly set the color of the child element (the span) inside the .page_number element to be black. Now on you mouse enter you are setting the color on the page_number element, but since the child has a style applied directly to it (i.e. color: black) it does not inherit the parent style. Inline styles (i.e. style applied directly to the element with the style="" attribute, which is what JS does) always have the highest precedence. This is why it is generally not best practice to put inline styles on an element, as you have just seen, they are pretty much impossible to override. So change either the child to not have an explicit style, or on the mouse enter change the child not the parent
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].children[0].style.color = "black"
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].children[0].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].children[0].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
or
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
but as I indicated all this should really be in CSS
You trying to change color of a instead of span
Try like this
obj[i].children[0].style.color = "red"
JSFIDDLE

How to dynamically add a CSS class and implement its style in JavaScript

Hi I'm new to JavaScript and CSS and I would like to create a JavaScript function that dynamically applies the style properties that are defined inside this function to a specific element.
Please check my code below, I have managed to create the element and add the class to that element but I'm struggling to implement the style properties inside this function.
function highlight(){
var styl = document.querySelector("#element_to_pop_up");
styl.style.cssText = " background-color:#fff;border-radius:15px; color:#000;display:none;padding:20px;min-width:30%;min-height: 30%;max-width:40%; max-height: 40%;";
styl.className = styl.className + "b-close";
//.b-close{
//cursor:pointer;
//position:absolute;
//right:10px;
//top:5px;
//}
}
Please any help will be highly appreciated.
If you want to add a style class to your page and write its style content, you should create it first then put it in a <style> tag, so you can use it later.
This is your way to go:
function highlight() {
var styl = document.querySelector("#element_to_pop_up");
//Create StyleSheet
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right:10px;\n top:5px;\n}");
//Put the style on it.
styleSheet.appendChild(text);
//Append it to <head>
document.head.appendChild(styleSheet);
//Apply it
styl.className = styl.className + " b-close";
}
<div onclick="highlight()" id="element_to_pop_up">bla bla bla</div>
Create a Style Sheet Element.
Put the style on it.
Append it to the head of the document.
Use this style or apply it to element.
EDIT:
If you will pass the style top and right values as parameters to the function just do the following:
function highlight(right, top) {
var styl = document.querySelector("#element_to_pop_up");
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right: "+right+"px;\n top: "+top+"px;\n}");
styleSheet.appendChild(text);
document.head.appendChild(styleSheet);
styl.className = styl.className + " b-close";
}
Use jquery insted on javascript.
$(selector).css("width":"100%").css("height","100px");
You can just add a CSS class (and style it in your stylesheet instead of your javascript).
Here is an example (there are multiple way to do it but I don't know what your try to achieve exactly) :
function highlight(){
var target = document.getElementById("header");
target.className = target.className + " highlighted";
}
var btn = document.getElementById('add-class');
btn.addEventListener('click', highlight);
.highlighted {
/*Your CSS*/
background-color: red;
}
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>
Edit: If you want to use jQuery, it's even simpler :
$(document).ready(function() {
$('#add-class').on('click', function() {
$('#header').toggleClass('highlighted');
});
});
.highlighted {
/*Your CSS*/
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>

How to return a javascript set style property to CSS default

I'm trying to work out how, after changing style properties with javascript, I can revert to the value in the stylesheet (including the units).
In the example below, I'd like the output to read 100px (the value in the CSS), rather than 10px, as getComputedStyle gives.
I'd also keep the dummy div at top:25px, so removing the style property won't work.
The best I have is cloning the node and reading the height and storing in a property (http://jsfiddle.net/daneastwell/zHMvh/4/), but this is not really getting the browser's default css value (especially if this is set in ems).
http://jsfiddle.net/daneastwell/zHMvh/1/
<style>
#elem-container{
position: absolute;
left: 100px;
top: 200px;
height: 100px;
}
</style>
<div id="elem-container">dummy</div>
<div id="output"></div>
<script>
function getTheStyle(){
var elem = document.getElementById("elem-container");
elem.style.left = "10px";
elem.style.top = "25px";
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("left");
document.getElementById("output").innerHTML = theCSSprop;
}
getTheStyle();
</script>
Just clear the inline style you wish to fallback to original stylesheet on.
elem.style.left = null;
The style object has a built-in removeProperty() method, so you could do something like:
elem.style.removeProperty('left');
As far as I know, this will have exactly the same effect as setting the property to null, as abaelter suggested. I just thought it might be worth including for the sake of completeness.
Combining abaelter's answer and http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ gives us the below function:
var getCssStyle = function(elementId, cssProperty) {
var elem = document.getElementById(elementId);
var inlineCssValue = elem.style[cssProperty];
// If the inline style exists remove it, so we have access to the original CSS
if (inlineCssValue !== "") {
elem.style[cssProperty] = null;
}
var cssValue = "";
// For most browsers
if (document.defaultView && document.defaultView.getComputedStyle) {
cssValue = document.defaultView.getComputedStyle(elem, "").getPropertyValue(cssProperty);
}
// For IE except 5
else if (elem.currentStyle){
cssProperty = cssProperty.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
cssValue = elem.currentStyle[cssProperty];
}
// Put the inline style back if it had one originally
if (inlineCssValue !== "") {
elem.style[cssProperty] = inlineCssValue;
}
return cssValue;
}
Placing in your example code and testing:
console.log("getCssStyle: " + getCssStyle("elem-container", "left"));
Gives us getCssStyle: 100px allowing you to see the original CSS value. If you just want to revert the value then do as abaelter says and null the CSS value you want to revert.

Categories

Resources