I'm writing a HTML webPage, I use a button and I need to change his background-color on mouseover using a javascript function.
Here is the code.
<button onmouseover="funzione(this)">BTN</button>
<script>
funzione(x){
x.style.background-color=#ffffff;
}
</script>
In JavaScript you need get handler to element x e.g.:
var x = document.getElementById("x");
but you should do this with CCS:
button{
background-color: yellow;
}
button:hover{
background-color: lime;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:hover
This is very basic. You're missing keyword function, and with that style of accessing properties, you need to use camel case. Finally, wrap the color hex within quotes.
function funzione(x){
x.style.backgroundColor= '#ffffff';
}
<button onmouseover="funzione(this)">BTN</button>
The recommended way is use CSS in production, but if you're just into JavaScript and want to explore, it's fine.
If you want in js:
<button onmouseover="set_color(this)">BTN</button>
<script>
function set_color(x){
x.style.backgroundColor='red';
}
</script>
function funzione(x){
x.style.backgroundColor = "#ffffff";
}
<button onmouseover = "funzione(this)">BTN</button>
You can do this simply in CSS, its easy, efficient and less code.
<style type="text/css">
.myHoverButton:hover { background-color: #ffffff; }
</style>
<button id="button1" class="myHoverButton">
Related
If i have the library materialize and an element "h1", how do i change only its background color "black" to "white" using javascript? For example using a button.
<h1 class="black red-text">Test</h1>
Give the element an id:
<h1 id="test" class="black red-text">Test</h1>
Then you can select it like the following:
var el = document.getElementById('test');
You can then just remove the class black with this code:
el.classList.remove('black');
And append the new class:
el.classList.add('white');
Create a function and a white class. Inside the function use document.getElementsByClassName . Since document.getElementsByClassName is a collection so you need to use index like [0] to access it
function changeColor() {
document.getElementsByClassName("black")[0].classList.add('white')
}
.white {
background: white !important;
}
.black {
background: black;
}
.red-text {
color: red;
}
<h1 class="black red-text">Test</h1>
<button onclick='changeColor()'>Change Color</button>
Here is the answer.
Select the element using document. getElementById
and on button click
You can use title.classList.toggle("white"); to toggle given class.
const button = document.getElementById('btn');
const title = document.getElementById('title');
btn.addEventListener('click', () => {
title.classList.toggle("white");
});
.red-text {
color: red;
}
.black {
background-color: #000;
}
.white {
background-color: #fff;
}
<h1 id="title" class="black red-text">Test</h1>
<button id="btn">Change Bg</button>
Hope this resolves your problem. just check the condition whether the class already exist if not add it.
let h1 = document.querySelector(".red-text");
let btn = document.querySelector("#btn");
function changeColor(){
if(h1.classList.contains("black")){
h1.classList.remove("black");
h1.classList.add("white");
}else{
h1.classList.add("black");
h1.classList.remove("white");
}
}
btn.addEventListener("click", changeColor);
.black{
background: black;
color: red
}
.white{
background: white;
}
<h1 class="black red-text">Test</h1>
<button id="btn">Change Color</button>
One approach that keeps things neat and tidy in terms of Materialize conventions could be to add or remove classnames, and thus triggering pre-existing styles. Note, you may need a more specific selector if you have multiple elements that share the class:
document.querySelector('h1.black').classList.add('white');
Materialize already has a vast array of colour classes so no need to create new ones.
Codepen here:
And just for clarification:
document.querySelector('h1.black') - this finds the element with a matching class. You could also use ID to be more specific, while
.classList retrieves all the classes applied to that element (in this case .black and .red-text) and .add('white') - well, that adds the class you state in the brackets.
I need to change dynamically my css properties. I know that the right way to do it is with: document.getElementById("XXXX").style.fontSize = "xx-large";
However, when I have this css:
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
I haven't been able to find the way to access it, and I have tried any possible permutation (nothing works!):
document.getElementById("year1.subdomain-text").style.fontSize = "xx-large";
document.getElementById("year1").style.fontSize = "xx-large";
document.getElementById("subdomain-text").style.fontSize = "xx-large";
document.getElementById("#year1.subdomain-text").style.fontSize = "xx-large";
....
Any idea how to make it happen?
Thanks!
You are using .getElemenByID() which means you specify just the ID name no need to include the class name i.e. document.getElementById("year1").style.fontSize = "xx-large";
Example here :http://jsfiddle.net/Nb7wy/1770/
document.getElementById retrieves html element by its id attribute. In your case, it should be:
document.getElementById("year1")
If the id is unique, as expected, the class is not necessary for the selector in the css rule either. You could just remove the class from your css rule.
For other cases where combining selectors is needed, it can be used document.querySelector(css_selector) (instead of document.getElementById).
Working code:
<html>
<head>
<style>
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
</style>
</head>
<body>
<p id="year1" class="subdomain-text">Texto prueba</p>
<input type="button" onclick="test();" />
<script>
function test() {
document.getElementById("year1").style.fontSize = "xx-large";
}
</script>
</body>
</html>
I am working on making a number list with each number on its individual div. So far I am able to remove the div with Javascript (on click), but I would like to enable JQuery so that I am able to add a class to a div and then remove all divs of that class with a button or something like that.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
h4 {
font-family: Verdana;
color: black;
text-decoration: none;
}
</style>
</head>
<body>
<h4>Double click para borrar un numero</h4>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
divTag.ondblclick = function(){this.parentNode.removeChild(this)};
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
http://jsfiddle.net/ramonfabrega/AZSy8/
For simplicity, I just tried hiding the div's clicked, but JQuery does not seem to work. So something must be off.
Two issues:
1) jQuery wasn't loaded.
2) You were trying to bind the click event on an invalid selector (divTag instead of div)
Here's an updated fiddle: http://jsfiddle.net/LFC3A/2/
Regarding #2 - jQuery allows you to select an element multiple ways. The most common is to use a selector. The majority of selectors jQuery supports are from CSS 1 - 3, though jQuery supports some of its own custom selectors (such as div:eq, div:gt, and so on...) Check out the selectors page here: http://api.jquery.com/category/selectors/
Now, if your markup was:
<body>
<divTag>My Custom Div Tag</divTag>
<div>My regular DIV</div>
</body>
Then your original fiddle would have worked. In fact, here's an updated fiddle demonstrating that: http://jsfiddle.net/FpMAw/ (I updated your createElement to return a custom element, divTag)
The other way of accessing jQuery is by passing it a DOM element. Something like:
var $body = $(document.body) is equivalent to var $body = $('body')
If you reference that, you now have a jQuery object with a bunch of useful helper methods. So, in our previous example, we can now do:
$body.css('color', 'red')
Hopefully this helps explain a bit more why it didn't work. If you have any other questions, feel free to ask :)
Fiddle Demo
you are not including jQuery library in the fiddle
change $('divTag') to $('div')
Read $( "element" )
$(document).ready(function () {
$('div').click(function () {
$(this).hide();
});
});
Start Learning
jQuery API Documentation
This will create and add a click handler at the same time.
$('<div>').click(function(e){ this.addClass('active');})
I'm making a collapsible treeView.
I made it all, I just need my + and - icons to toggle whenever they are clicked.
I did the part when I change an icon from + to -, on click, with jQuery with the following code:
$(this).attr('src','../images/expand.gif');
Problem is, I don't know how to make it go other way around, when i click on the node again :)
This should work:
<style>
.expand{
content:url("http://site.com/expand.gif");
}
.collapse{
content:url("http://site.com/collapse.gif");
}
</style>
<img class="expand">
<script>
//onclick code
$('img.expand').toggleClass('collapse');
</script>
Look for jquery function toggleClass :)
http://jsfiddle.net/Ceptu/
Html:
<div id="box">
Hello :D
</div>
Jquery:
$("#box").click(function () {
$(this).toggleClass("red");
});
Css:
#box {
width: 200px;
height: 200px;
background-color: blue;
}
.red {
background-color: red !important;
}
Remember that !important is realy important!!!
Lots of ways to do this :D
I wanted to do this without making classes. Inside your click event function, you could do something like this:
if($(this).attr('src') == '../images/collapse.gif')
$(this).attr('src', '../images/expand.gif');
else
$(this).attr('src', '../images/collapse.gif');
add plus as a default img src then define a minus-class to change the image source to minus image
$("selector_for_your_link").click(function () {
$(this).toggleClass("minus-class");
});
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}