I'd like to change the css "background-image:" when someone clicks a button.
I'm not sure if I'm able to change it through css or if I would need to incorporate java script. Also, if I need java script what type of code would I need?
My current work around is with css and it looks like:
.hello-button {
background-image: url("hello.png");
background-repeat: no-repeat;
background-attachment: inherit;
background-position: center;
-webkit-transition: 2s ease-out;
-moz-transition: 2s ease-out;
-o-transition: 2s ease-out;
transition: 2s ease-out;
}
.hello-button:hover {
background-image: url("bye.png");
background-repeat: no-repeat;
background-attachment: inherit;
background-position: center;
transition-delay: .7s;
-webkit-transition-delay: .7s;
-moz-transition-delay: .7s;
-o-transition-delay: .7s;
}
I'd approach it like this. http://jsfiddle.net/darcher/6Ex7h/
jquery
$('.img').on({
click: function(){
$(this).addClass('new-bg').removeClass('bg') // changes background on click
},
mousedown: function() {
// :active state
},
mouseup: function() {
// on click release
},
mouseenter: function() {
// on hover
},
mouseleave: function() {
// hover exit
}
/*
, hover: function(){
// or hover instead of enter/leave
}
*/
})
With these varying states, you can do anything you need. There are also a variety of other states you can use http://api.jquery.com/category/events/mouse-events/
html
<div href="#" class="img bg"></div>
css
.img{
background-repeat:no-repeat;
background-size:cover;
background-position:center;
display:block;
height:200px;
}
.bg{
background-image:url(http://placehold.it/300x200/white/black);
}
.new-bg{
background-image:url(http://placehold.it/300x200/black/white);
}
there are css only alternatives, but they're not really great on support: http://tympanus.net/codrops/2012/12/17/css-click-events/
You could use javascript for change the background. The following website javascripter is an example of changing background color and manipulating CSS by Javascript. I hope this can help you.
1. CSS pseudo-class selector:active
If you didn't care about persistence you could always use the the pseudo-class ":active". The image will only be affected as long as your mouse is down. As soon as you mouse-up it'll revert. At this moment, that's about as close as you can get in CSS.
.hello-button:active {
background-image: url("image.jpg");
}
JSFiddle Example: http://jsfiddle.net/pkrWV/
2. Change Style Attribute with JavaScript
JavaScript is just about the only way you're going to be able to click on an object, mouse-up and the background is still changed. JavaScript gives you a couple ways to do it too.
You can use JavaScript to change the object's style attribute to update the 'background-image'.
obj.style.backgroundImage = 'url("image.jpg")';
JSFiddle: http://jsfiddle.net/pkrWV/1/
3. Change Class Attribute with JavaScript
Or similarly, you could create two classes in your CSS, and use JavaScript to update the object's class attribute.
/* JavaScript */
obj.className = 'imageOneClassName';
/* CSS */
.imageOneClassName {
background-image: url("image.jpg");
}
JSFiddle: http://jsfiddle.net/pkrWV/2/
My personal favorite method is the third option where you still use CSS to style your obj in different states, and then you use JavaScript to change the class name to update those states. It's less JavaScript, more CSS, and you're keeping everything in their appropriate places.
$(function() {
$('.home').click(function() {
$(this).css('background-image', 'url(images/hello.png)');
});
}):
you have to do like this, there was a relative question see this i hope i helped you...
jquery onclick change css background image
There's no way to do this in pure HTML/CSS, but in javascript you can do it like so:
var button = document.getElementsByClassName("hello-button")[0];
button.addEventListener("click", function(){
button.style.backgroundImage = "url(bye.png)";
});
You can either include this in a <script></script> tag or add it to a .js file and include that by adding <script src="scriptName.js"></script>
Here's a CSS-only solution: http://jsfiddle.net/VVj6w/
HTML
<input type = "checkbox" id = "backgroundToggle" />
<label for = "backgroundToggle">Switch Background</label>
<div id = "wrapper"></div>
CSS
* {
padding: 0;
margin: 0;
border: 0;
}
html, body {
height: 100%;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
input[type = "checkbox"] {
display: none;
}
label {
position: absolute;
top: 10px;
left: 10px;
background-color: #eee;
border: 2px solid #ccc;
padding: 5px;
border-radius: 10px;
font-family: Arial, Sans-Serif;
cursor: pointer;
}
#wrapper {
background-color: hsla(0, 100%, 50%, 1);
height: 100%;
width: 100%;
}
input[type = "checkbox"]:checked ~ #wrapper {
background-color: hsla(0, 100%, 50%, 0.1);
}
If you only want it to change while you are clicking, you should be able to use
.hello-button:active {
background-image: url("bye.png");
...
}
If you want it to remain that way after the click (after the mouse button has been released), you will have to use javascript. Something like the following
document.getElementsByClassName("hello-button")[0].addEventListener("click", function(el) {
el.classList.add("clicked");
});
Then in the CSS, update your selector to
.hello-button.clicked
Related
Using JavaScript's click simulation does not work for CSS pseudo-class :active. After I tried some classList methods, it still doesn't work. I just wonder if there are some possible ways to realize that?
Run the snippet below and click the button to see the ripple effect. The ripple effect doesn't repeat automatically with the included setInterval code that simulates a click. It only works with the real click of the button:
const btn = document.querySelector(`button`);
btn.addEventListener(`click`, (e) => {
console.clear();
// try to manually set pseudo-class `:active` ?
btn.classList.toggle('ripple', 'ripple:active');
console.log('classList =', e.target.className);
});
setInterval(() => {
// js simulator click doesn't work for css pseudo-class `:active`
btn.click();
}, 1000);
.ripple {
position: relative;
overflow: hidden;
}
.ripple:after {
content: "";
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
background-image: radial-gradient(circle, #000 10%, transparent 10.01%);
background-repeat: no-repeat;
background-position: 50%;
transform: scale(10, 10);
opacity: 0;
transition: transform .5s, opacity 1s;
}
.ripple:active:after {
transform: scale(0, 0);
opacity: .2;
transition: 0s;
}
<button class="ripple">ripple button</button>
References
https://developer.mozilla.org/en-US/docs/Web/CSS/:active
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
It is impossible according to the API description so far.
The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user.
When using a mouse, "activation" typically starts when the user presses down the primary mouse button.
APIs
https://developer.mozilla.org/en-US/docs/Web/CSS/:active
https://drafts.csswg.org/selectors/#the-active-pseudo
https://html.spec.whatwg.org/multipage/semantics-other.html#concept-selector-active
You can try to recreate "active" event using js and css
CSS :
.ripple {
background-color: red;
}
.ripple:active, .ripple.active {
background-color: green;
}
JS :
let btn = document.querySelector('.ripple');
btn.addEventListener('click', e => {
btn.classList.add('active');
setTimeout(() => {
btn.classList.remove('active');
}, 500);
});
setInterval(() => {
console.log('click');
btn.click();
}, 2000);
I found a way to change the langauge:
<h2 class="fr_lang">Français</h2>
<h2 class="en_lang">English</h2>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
#lang-switch img {
width: 32px;
height: 32px;
opacity: 0.5;
transition: all .5s;
margin: auto 3px;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
#lang-switch img:hover {
cursor: pointer;
opacity: 1;
}
.fr_lang,
.en_lang {
display: none;
transition: display .5s;
}
/* Language */
.active-lang {
display: flex !important;
transition: display .5s;
}
.active-flag {
transition: all .5s;
opacity: 1 !important;
}
$(document).ready(function(){
// By default
$('.en_lang').addClass("active-lang");
$('#lang-switch .en').addClass("active-flag");
// Function switch
$(function() {
// French button
$("#lang-switch .fr").click(function() {
// Enable French
$('.fr_lang').addClass("active-lang");
// Disable English
$('.en_lang').removeClass("active-lang")
// Active or remove the opacity on the flags.
$('#lang-switch .fr').addClass("active-flag");
$('#lang-switch .en').removeClass("active-flag");
});
// English button
$("#lang-switch .en").click(function() {
// Enable English
$('.en_lang').addClass("active-lang");
// Disable French
$('.fr_lang').removeClass("active-lang")
// Active or remove the opacity on the flags.
$('#lang-switch .en').addClass("active-flag");
$('#lang-switch .fr').removeClass("active-flag");
});
});
});
This works find but my project includes many different sites.
How to keep the changed language for all sites/the hole project?
And is it possible to change the button text too? Or should I give the button the language class and create a new button with the other language class?
Thank you :)
If all your sites run on the same domain you can use localStorage to store last language used.
Otherwise you will need a 'mediator' like a server to store the data.
In the example below, I want to change pad's color via JS to green, but also make it transition to yellow when it is active.
However, changing the color via JS like this: pad.style.background = 'green' will make the transition stop working. If I remove this line, the transition will work fine.
Why is that so and how can I fix this?
let pad = document.getElementsByClassName('pad')[0]
pad.style.background = 'green'
.pad{
width: 80px;
height: 80px;
background: black;
transition: background .5s;
}
.pad:active {
background: yellow;
}
<!DOCTYPE HTML>
<body>
<div class="pad"></div>
</body>
The reason for not working is because pad.style.background will add an inline css style which has a priority over a css class
Solution:
use a class instead of inline style like in the code bellow:
let pad = document.getElementsByClassName('pad')[0]
pad.classList.add("green");
.pad {
width: 80px;
height: 80px;
background: black;
transition: background .5s;
}
.pad.green {
background: green;
}
.pad:active {
background: yellow;
}
<div class="pad"></div>
It seems like JS is adding green to the :active state too.
Add !important to the active style in your css to make it more of a priority:
.pad:active {
background: yellow!important;
}
This is happening because you're overriding the existing style by applying the style via style attribute on the HTML element.
Instead you should create a new class and apply that using JavaScript, in that case the original styles won't be overidden and the transition would still work
Have your CSS as:
.pad {
width: 80px;
height: 80px;
background: black;
transition: background .5s;
}
.pad:active {
background: yellow;
}
.pad-green {
background: green;
}
And then in your JavaScript, do this:
let pad = document.getElementsByClassName('pad')[0]
pad.classList.add('pad-green')
Hope that helps, let me know in the comments if there are any questions.
Quick question. I'm using jquery to target the "src" attribute of the logo on my website. So when the navbar shrinks (on scroll) the logo changes to a lighter version of the same image.
This worked PERFECTLY when I was making the site locally in HTML. It even worked perfectly when I uploaded the HTML to my web-host. However as I've started to move my site into a Wordpress theme, there is about a second delay in the image switch over. I was wondering If someone could take a look at my site and tell me what the problem might be? - Like I said, it was working perfectly locally and uploaded as plain HTML. Do I need to somehow preload the second image in jquery?
My URL is: http://iwebyou.com.au - Scroll down and notice when the navbar shrinks, there is a delay in the logo switching over. Also please ignore the rest of my website, its unfinished and everything else is a complete mess right now haha..
Cheers
Without seeing your code, it's difficult to help further, but IMO the best solution would be to set the logo as a background-image via CSS classes and then change the css class with javascript when needed, rather then modifying an image src attribute.
<div class="logo logo-dark">Company Name for SEO</div>
and
<div class="logo logo-light">Company Name for SEO</div>
css:
.logo-dark {
background-image: #fff url('path to dark logo') no-repeat center center;
}
.logo-light {
background-image: #fff url('path to light logo') no-repeat center center;
}
.logo {
// common logo styles
}
Here's an example using opacity and transition:
window.addEventListener('scroll', e => {
const nav = document.querySelector('.nav');
if(window.scrollY > 50) {
nav.classList.add('dark');
}else {
nav.classList.remove('dark');
}
});
img {
width: 200px;
position: absolute;
top: 0;
left: 0;
transition: all 500ms ease;
}
.light {
opacity: 0;
}
.nav {
background: white;
position: fixed;
top: 0;
height: 60px;
width: 100%;
transition: all 500ms ease;
}
.nav.dark {
background: black;
}
.nav.dark .dark {
opacity: 0;
}
.nav.dark .light {
opacity: 1;
}
.content {
height: 1000px
}
<div class="content">
<div class="nav">
<img src="https://www.iwebyou.com.au/wp-content/uploads/2018/06/cropped-I-Web-YouDark-2.png" class="dark" />
<img src="https://www.iwebyou.com.au/wp-content/uploads/2018/06/I-Web-YouLight-2.png" class="light" />
</div>
</div>
function toggle(){
var button=document.querySelector('.toggle');
var bar=document.querySelector('.slide');
if(bar.className==='slide up'){
bar.className='slide down';
}else{
bar.className='slide up';
}
}
*{
margin:0px;
padding:0px;
height:100%;
width:100%;
}
.box{
overflow:hidden;
background-image: url('http://tombricker.smugmug.com/Travel/San-Francisco-California/i-jk2Z7D7/0/L/san-francisco-golden-gate-bridge-morning-sun-bricker-L.jpg');
background-size: cover;
background-position:center;
}
.slide{
position: relative;
left:39vw;
width: 55vw;
height: 75vh;
background: red;
}
.slide:before {
content: '';
position:absolute;
top:-3vh;
width: 0px;
height: 0px;
border-left:27.5vw solid transparent;
border-right:27.5vw solid transparent;
border-bottom:3vh solid white;
}
.slide.down{
transform:translateY(100vh);
}
.slide.up{
transform:translateY(25vh);
}
.slide{
transition:transform 0.4s ease-out;
}
<div class='box'>
<div class='slide up' onclick='toggle()'></div>
</div>
The white triangle on top of the red rectangle is made with pseudo element :before. What I am trying to do is when the sliding tag is up, the white triangle should be pointing down. To do that, I want to write a JS code that will add a transform CSS to that class with pseudo element that will translate triangle down by its height and rotate by 180deg.
I find on this developer blog the JS code to add, but it does not work and I don't know how to delete that code when the tag is down.
function toggle(){
var button=document.querySelector('.toggle');
var bar=document.querySelector('.slide');
if(bar.className==='slide up'){
bar.className='slide down';
//Here is where I need to add the line to delete CSS
}else{
bar.className='slide up';
//This is to add CSS
//3vh is the height of that white triangle
document.styleSheets[0].addRule('.slight:before','transform:translateY(3vh) rotateX(180deg)');
}
}
You can add the transformation to the CSS class, and simply toggle it.
CSS
.slide.up:before {
transform: translateY(3vh) rotateX(180deg);
}
JS
var bar = document.querySelector('.slide')
function toggle() {
var cl = bar.classList
cl.toggle('down', cl.contains('up'))
cl.toggle('up', !cl.contains('down'))
}
JSFiddle demo: https://jsfiddle.net/htq8ouyn/2/
Resources
Element.classList - Web APIs | MDN