style the thumb of range input with jquery [duplicate] - javascript

This question already has answers here:
change background image of webkit-slider-thumb by jquery
(4 answers)
Closed 7 years ago.
I have some sliders which I want to style via jquery
For example:
<input type="range"/>
To style it with plain css I would write:
input[type="range"]::-webkit-slider-thumb{
/* blah blah blah*/
background:red;
}
This is working.
However if I try this:
$("input[type='range']::-webkit-slider-thumb").css("background","red");
It will not give me an error but it also will not work.
I have seen some other similar questions .The answer to these questions were to insert a new style tag with jquery and some classes(Something i don't want to do).Is there any way to style ::-webkit-slider-thumb with jquery?
UPDATE
I don't want to inject any new style tags to my html or use custom classes!!!

Plain JavaScript could work for this:
for(var j = 0; j < document.styleSheets[1].rules.length; j++) {
var rule = document.styleSheets[1].rules[j];
if(rule.cssText.match("webkit-slider-thumb")) {
rule.style.backgroundColor="red";
}
}
Here is an Example
Because ::-webkit-slider-thumb is pseudo-element jQuery cannot select it, which leaves you with limited options to style this.
You could optionally use jQuery:
$("input[type='range']").addClass('slideThumb');
and then using CSS add:
.slideThumb::-webkit-slider-thumb {
background: red;
}
but this would be equivalent of simply adding the class directly onto your input:
<input class="slideThumb" type="range"/>

CSS
.redslider::-webkit-slider-thumb {
background-color: red;
}
jQuery
$('input[type=range]').addClass('redslider');
Why?
::-webkit-slider-thumb isn't actually a selector. It's like setting an :active through a style attribute which isn't possible. That makes it so we have to make it in a class and add it. You could use document.styleSheets but that is ambiguous, complicated, and is overkill for a simple task such as this

Related

SVG Object classList.add() is adding the class to the element but not linking back to the stylesheet [duplicate]

This question already has answers here:
How to apply CSS to iframe?
(28 answers)
How do you style a external svg with css
(1 answer)
Closed 3 years ago.
I am working on a custom Wordpress Theme run on my localhost server. I am having trouble figuring out why the class is being added to the classList, but the style elements are not applying.
Javascript: "custom.js"
$(document).load(function() {
changeColor();
});
function changeColor(){
var x = document.getElementById("icon").contentDocument;
var y = x.querySelectorAll("path, circle");
for(var i = 0; i < y.length; ++i) {
y[i].classList.add("icon_stroke");
}
}
External CSS Stylesheet: "style.css"
.icon_stroke {
stroke: red;
}
HTML/PHP: "front-page.php"
<object id="icon" data="<?php bloginfo('template_directory');?>/src/imgs/icons/balance_icon_light_circle.svg" type="image/svg+xml"></object>
I can see in the Chrome editor that it successfully adds the class to the classList of the SVG element, however, there is no styling change to the SVG. I assume this might have something to do with the external stylesheet interacting with an external SVG object. I have (a) attached screenshot(s) for further clarification. Please let me know if you understand what is causing this issue, or if you have a workaround solution.
Thanks!!!!

Javascript - How to get all matching classes and selector from css files for an element [duplicate]

This question already has answers here:
Find all CSS rules that apply to an element
(10 answers)
Closed 8 years ago.
It's a little hard to explain what I want to do, So I'll try to do it with an example.
Lets say I have this HTML:
<ul>
<li id="myli" class="myclass">Hello</li>
</ul>
and the following css
.myclass{
color:red;
}
li.myclass{
background-color:black;
}
ul li{
float:left;
}
Now, I want to create a function in JS that get a DomElement and gets all the matching selectors from the css files for this element (like the F12 toolbar in chrome that shows all styles for an element) like the following:
var mySelectors = GetSelectorsForElement(document.getElementById("myli"));
and the content of mySelectors will be
[".myclass",
"li.myclass",
"ul li"]
Can this be achieved in JS?
With the way you described it, it looks like you'll already have the id, if you also wanted to get the classes, you could do something like this:
window.getMatchedCSSRules(document.getElementById("id"));
If you don't want to use the Webkit-native getMatchedCSSRules because of (lack of) browser support, you could simply try the following function:
function css(a) {
var sheets = document.styleSheets, o = [];
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o.push(rules[r].selectorText);
}
}
}
return o;
}
JSFiddle: http://jsfiddle.net/HP326/
Adapted from Can jQuery get all CSS styles associated with an element?
window.getMatchedCSSRules(document.getElementById("myli"));

How can I write the javascript script to modify this css file?

Directory Structure:
index.html
--admin
----suit.css
And the part of the css file is:
#suit-left{width:200px;right:240px;margin-left:-100%}
.suit-columns{padding-left:200px;padding-right:40px;}
I want to write a javascript code in the index.html:
<button onclick="">Change CSS</button>
to change the css file like this:
#suit-left { display: none; }
.suit-columns { padding-left: 0; }
How can I do this?regards,thanks a lot
If you want the apply css on particular element by javascript, do something like this.
<button onclick="changeCss()">Change CSS</button>
UPDATE
<script>
function changeCss(){
var suitInput = document.getElementById('suit-left');
suitInput.style.display = 'none';
//UPDATED the answer
var siteCol = document.getElementsByClassName('suit-columns')[0];
siteCol.style.paddingLeft = '0';
//siteCol.style.paddingRight = '0'; //incase of want padding right 0
}
</script>
What I would recommend here is to manipulate the classes associated with the element rather than changing the class definition itself.
Here is a simple example:
.sideBar{ /* your normal rules here */ }
.sideBar.hidden { display:none; }
In order to hide your sidebar, all you'd have to do is add the hidden class name to the element.
In this way, you would define CSS rules for your sidebar when it is open, and different rules for when it is closed. Once you have those two states pre-defined, all you'll have to do is change/add/remove the class to hide/display your sidebar.
I feel like this was the main issue with your question here. The other tasks you wish to perform such as clicking on a button or actually manipulating the class attribute has been covered in many posts already. Here are some useful links for you -
Add class to given element
Using an HTML button to call a JS function
You can write the script in this way and paste below script at head block of index.html
I assume that you have knowledge of jquery.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
function ChangeCss(){
$('#suit-left').css('display','none');
$('.suit-columns').css('padding-left','0');
}
<script>
<button onclick="ChangeCss();" >
Now it will help!
So basically using css function of jquery you can change css/style attributes.
I hope it will help you.

Can't change background of div region using javascript?

This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}

Need Javascript syntax to reference a CSS class instead of HTML element

I searched online for the correct syntax to reference a CSS class, instead of an HTML element, but was unable to find anything helpful.
I would like to modify the code below to reference any DIV of class buy_content "div.buy_content" instead of the body element.
Small Text
Medium Text
Large Text
There is no "JavaScript syntax" for what you're asking for. Newer browsers support an API called "getElementsByClassName", so you could do this:
function setSize(sz) {
var elements = document.getElementsByClassName('buy_content');
for (var i = 0; i < elements.length; ++i) {
if (elements[i].tagName === 'DIV')
elements[i].style.fontSize = sz;
}
}
<a href='#' onclick='setSize("1em"); set_cookie(...);'>Small</a>
You can find a "patch" for "getElementsByClassName" support here.
<a href="#" class="clickie size-1" >Small text </a>
<a href="#" class="clickie size-2" >Medium text </a>
<a href="#" class="clickie size-3" >Large text </a>
You should change the markup not to rely on inline javascript.
// bind the event handler to all <a> tags
var as = document.getElementsByTagNames("a");
for (var i = 0, ii = as.length; i < ii; i++) {
as[i].onclick = setText;
}
function setText(ev) {
// get the em size from the class
var size = /[.]*text-([\d][.]*)/.exec(ev.target.className)[1]
var divs = document.querySelectorAll("div.buy_content");
// set the style on all divs.
for (var i = 0, ii = divs.length; i < ii; i++) {
divs[i].style.fontSize = size + "em";
}
}
There are issues with browser support (mainly IE7 and lower) so you need some more boilerplate to make it work.
You can't really do this (easily/readably/cleanly) with inline and stock JavaScript because the JavaScript DOM API doesn't provide a way to reference a CSS class since this isn't part of the DOM. You would have to populate an array or list with HTML elements that have that class applied to them and then iterate over the collection.
JQuery provides selectors and iterators to make this very simple, but if you can't use libraries then doing this inline isn't a good idea. Put it in a function in a script block or an external .js file.
EDIT:
A few people pointed out querySelectorAll, which will select by class but from what I have read isn't completely cross platform (doesn't work on IE below IE 8).
Further, to clarify on my original post, when I said that the DOM API doesn't allow you to access an element by class, what I meant was that it couldn't be done with DOM traversal. querySelectAll or the JQuery selectors perform DOM traversal with functions that inspect elements and their properties, retrieve the objects, and populate collections. Even getElementById performs attribute inspection. I suppose, in retrospect, it's a moot point, but since he wasn't using selectors or attribute queries in his original code I thought that he was asking if there was JS syntax that was as simple as what he was currently using. That's why I mentioned functions. In my head, even something like getElementById is a function since, well, it is a function.
I believe what you are looking for is insertRule (this is exactly what you asked for... kinda):
document.styleSheets[document.styleSheets.length-1].insertRule('div.buy_content {font-size: 1em}',document.styleSheets[document.styleSheets.length-1].length)
document.styleSheets[document.styleSheets.length-1] is your last stylesheet.
the new rule will go at index document.styleSheets[document.styleSheets.length].length
http://www.quirksmode.org/dom/w3c_css.html#t22
also... deleteRule:
http://www.quirksmode.org/dom/w3c_css.html#t21
BUT, a better way to go would be to getElementsByClassName, loop through em, check their nodeName for "DIV", then apply the styles the old fashioned way.
Leverage CSS to do the selection work for you:
body.smalltext .buy_content { font-size: 1em; }
body.mediumtext .buy_content { font-size: 2em; }
body.largetext .buy_content { font-size: 3em; }
...
<input type="button" value="Small text" id="smalltext"/>
<input type="button" value="Medium text" id="mediumtext"/>
<input type="button" value="Large text" id="largetext"/>
...
document.getElementById('smalltext').onclick= function() {
document.body.className= 'smalltext';
};
document.getElementById('mediumtext').onclick= function() {
document.body.className= 'mediumtext';
};
document.getElementById('largetext').onclick= function() {
document.body.className= 'largetext';
};
My first suggestion to answer your exact question:
If your project is bigger in scope than just this one thing:
Download jQuery
Use code:
$('div.buy_content')
Which returns a jQuery array object of all the divs which you can further manipulate.
My second suggestion based on thinking more deeply about what you're trying to do:
Either completely replace the stylesheet in script or modify the existing stylesheet to change the style. Don't loop through all the DIVs in the document and change their style assignment, instead change the meaning of their already-assigned style.

Categories

Resources