i have a bar that is fixed to the bottom of the browser. i want to make the bar displayed as 'none', so that when a user hovers over the bar it is displayed until they hover out.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
html {
background: #34495e;
}
#pagebottom {
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
}
</style>
</head>
<body>
<div id="pagebottom">
random text
</div>
</body>
</html>
try this css solution
#pagebottom {
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
opacity:0;
}
#pagebottom:hover{
opacity:1;
transition:all .5s linear;
}
You can accomplish this with CSS. No JavaScript needed.:
#pagebottom {
opacity: 0;
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
}
#pagebottom:hover {
opacity: 1;
}
EDIT This is a jQuery solution. There are some great CSS only solutions above.
You can't display your div as none, as it will have no width or height, and therefore be un-hoverable. However, you can use the opacity attribute, and modify the footer's CSS accordingly.
Take a look at this JSFiddle
Here are the changes I made:
I added opacity: 0; to the #pagebottom CSS so it is invisible by default.
I added the following jQuery:
$('#pagebottom').mouseenter(function(){
$('#pagebottom').css('opacity','1');
});
$('#pagebottom').mouseleave(function(){
$('#pagebottom').css('opacity','0');
});
This code waits until the mouse enters the div area, and sets the opacity to 1. When the mouse leaves, it sets the opacity to 0 again, making the element invisible.
If you want a nice tradition so the div fades in and out, you can use CSS transitions or a jQuery plugin like Transit, or even the animate feature that Felix describes in his answer.
You can use:
1) css() to set the opacity of your div:
2) hover() to keep track of when the mouse pointer enters and leaves your div
3) animate() to apply fadeIn() and fadeOut animation when changing the opacity
$('#pagebottom').css('opacity','0');
$( "#pagebottom" ).hover(
function() {
$('#pagebottom').stop().animate({opacity: 1}, 500);
}, function() {
$('#pagebottom').stop().animate({opacity: 0}, 500);
}
);
Fiddle Demo
Related
I have a hover effect where when the icon image is hovered over, an larger image appears (for clarity). I want this larger image effect to end after three seconds AND still have the hover ability. If the image is moved off of, then came back to; I want the larger image to load for another three seconds. Every time the image is hovered over, the effect would last three seconds.
I have tried CSS animations, transitions, setTimeout and none of them are working like I need. Any help is appreciated. I have a LOT of code on this project, so I will try to only include the relevant parts. Thanks in advance.
I will have the code added to the question, once i figure out what I am doing wrong.
Code for building levels for hover image
#PlayerMarker1 {
position: absolute;
left:2%;
top: 2%;
z-index: 9;
}
#Player1Final{
position: absolute;
left:2%;
top: 2%;
z-index: 9;
}
/* Elements for Image load on hover*/
.playerMarker img{
margin: 0 5px 5px 0;
}
.playerMarker:hover{
background-color: transparent;
}
.playerMarker:hover img{
border: 1px;
}
.playerMarker span{ /*CSS for enlarged image*/
position: absolute;
padding: 0px;
left: -1000px;
/*background-color: black ;*/
visibility: hidden;
color: black;
text-decoration: none;
}
.playerMarker span img{ /*CSS for enlarged image*/
border-width: 0;
padding: 2px;
}
.playerMarker:hover span{ /*CSS for enlarged image*/
visibility: visible;
top: 0;
left: 100px; /*position where enlarged image should offset horizontally */
z-index: 50;
}
Code for defining the images.
<div id="Player1Test">
<a id="PlayerMarker1" href="#thumb1"><img src="Player Markers/Morty_Icon.png" width="auto" height="auto"/><span><img src="Player Images/Morty_Token.png" /><br /></span></a>
</div>
This script adds the playerMarker classes to the element I need.
/* Script to add class to player marker ID items */
function Player1Function() {
var Player1FinalTest = document.getElementById("PlayerMarker1");
Player1FinalTest.classList.add("playerMarker");
Player1FinalTest.id='Player1Final';
}
Seems like css animations to pulse the image would work fine. Run the code snippet to try.
img {
margin: 25px;
width: 100px;
height: auto;
}
img:hover {
animation: pulse 2s 1;
}
#keyframes pulse {
0% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.7);
}
50% {
transform: scale(1.4);
box-shadow: 0 0 0 10px rgba(0, 0, 0, 0);
}
100% {
transform: scale(1);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
}
<h4>Hover the mouse over image<h4>
<img src="https://stackoverflow.design/assets/img/favicons/apple-touch-icon.png">
Yogi has a good answer using an animation that could be adapted to clearly move your element. I wanted to add an answer manipulating the left and top values using delay.
You are essentially moving a hidden image from off screen onto the screen. Though this feels a bit strange to do, as there may be more clear ways of accomplishing this task, you can immediately move the left into view, and delay moving the top out of view.
A different delay is needed for the hover and for the base element, so it returns to the original position immediately and is available for reuse, but delays moving away on hover.
This might keep in spirit of your current project.
If you have any questions, please ask 🚀
.playerMarker {
background-color: lightblue;
--size: 4rem;
height: var(--size);
width: var(--size);
}
.playerMarker span {
position: absolute;
padding: 0px;
top: 0;
left: -1000px;
visibility: hidden;
color: black;
text-decoration: none;
transition: top 0s;
}
.playerMarker span img {
border-width: 0;
padding: 2px;
}
.playerMarker:hover span {
transition: top 0s 2s;
visibility: visible;
top: -1000px;
left: 100px;
z-index: 50;
}
<div class="playerMarker">
<span>
<img src="https://stackoverflow.design/assets/img/favicons/apple-touch-icon.png" />
</span>
</div>
Background
I have an HTML div which contains a ‘tooltip’-like feature (i.e., a text box pops up when a certain element is clicked or hovered over); this tooltip has decorative pseudo-elements to make it look like a ‘speech bubble,’ added in css as :before and :after .
I have a JS script, which is intended to show and hide the tooltip and decoration, in response to click events (i.e., toggle them between ‘show’ and ‘hide’ states).
Problem
I can’t get the decorative pseudo-elements to hide when the tooltip is hidden; as pseudo-elements, they are not part of the DOM and so I can’t use normal selectors to manipulate them.
When the tooltip is hidden on click, the decorative pseudo-elements persist, which is not a usable result.
I can’t do away with the decorative elements, they are part of the work specification.
Approach tried so far
Based on this question, my thought was to add an empty span with its own class, to which I’d prepend and append these pseudo-elements. Then, add or remove the class on click based on whether it exists already, or not.
I have also tried setting the class to which the pseudo-elements are pre/appended to display:none on click, but this also seems not to work
However, I cannot convince the pseudo-elements to hide on click.
I’ve included a screenshot of what these remnant pseudo-elements look like in the live environment.
Note: I tried to work up a running simulation for the purpose of this question, but I wasn’t able to and the original css file is massive; the code included below is for reference only.
All guidance is much appreciated!
const barContainer = document.querySelector(".bar-container");
const decorationElement = document.querySelector("#decoration");
document.addEventListener('click', function(event) {
console.log('click event listener triggered');
if (event.target.closest('.link') || event.target.classList.contains('link')) {
if (barContainer.classList.contains('open')) {
barContainer.classList.remove('open')
decorationElement.classList.remove('decoration')
document.querySelector('.tooltip-container').setAttribute('style', 'display:none');
} else {
barContainer.classList.add('open')
decorationElement.classList.add('decoration')
document.querySelector('.tooltip-container').setAttribute('style', 'display:block');
}
} else {
barContainer.classList.remove('open')
decorationElement.classList.remove('decoration')
document.querySelector('.tooltip-container').setAttribute('style', 'display:none');
}
});
.foo-container {
height: auto;
position: relative;
}
.bar-container {
height: auto;
position: relative;
text-align: center;
}
.bar-container:hover .tooltip-container,
.tooltip-container:hover,
.bar-container.open .tooltip-container {
position: absolute;
display: block;
text-align: left;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
bottom: 50px;
right: 5%;
border-radius: 4%;
font-weight: 300;
max-width: 90%;
font-size: 14px;
padding: 20px 0;
}
/*the below two rule sets create the rotated 'decoration' */
.bar-container:hover .tooltip-container:before,
.tooltip-container:hover:before,
.bar-container.open .tooltip-container:before,
.foo-container .bar-container:hover .decoration:before {
content: "";
width: 65px;
height: 35px;
position: absolute;
overflow: hidden;
transform: rotate(-180deg);
z-index: 10;
bottom: 0;
left: 170px;
background-color: white;
}
.foo-container .bar-container.open .decoration:before,
.foo-container .bar-container:hover .decoration:before {
content: "";
position: absolute;
width: 30px;
height: 30px;
background: #fff;
transform: rotate(45deg);
left: 30px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
z-index: 2;
top: -42px;
}
/* end 'deocration' */
<div class="foo-container">
<div class="bar-container">
<p>text <span class='link'>the-link<span id='decoration' class='decoration'></span></span>
</p>
<div class='tooltip-container'>
<p>lorem </p>
</div>
</div>
</div>
Screenshot of the undesirable 'persistent pseudo-elements' behavior -->
Here's the challenge:
I have two divs layered on top of one another in an HTML file. The top div is mostly transparent using CSS the bottom div has an image as its background. On mouseenter, I want the top div to disappear and on mouseleave I want the top div to come back.
$(document).ready(function() {
$('.dimmer').on('mouseenter', event => {
$(this).hide();
}).on('mouseleave', event => {
$(this).show();
});
});
.experience {
background: url("cmu-110.png") no-repeat center;
height: 110px;
width: 110px;
z-index: 2;
}
.dimmer {
background: rgba(238, 238, 238, .25);
position: relative;
top: -128px;
z-index: 3;
}
<div>
<div class="experience"></div>
<div class="dimmer"></div>
</div>
The jquery code snippet above is in a separate file and called in the html's head.
<head>
<!--- Some head stuff like title, meta, calling css in separate file, etc --->
<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="interaction.js"></script>
</head>
Full transparency: I am new to jquery and trying to use it for the first time. Despite working through the full codecademy jquery tutorial, reading w3C school tutorial, searching other stackoverflow posts, and spending more than a reasonable amount of time, I can't seem to get this to work--probably due to a dumb mistake.
Thank you for your help!
I believe a jquery '.on( "mouseout", handler )' on the bottom div should be sufficient to make the top div visible/fade in.
This post should help you: jquery .mouseover() and .mouseout() with fade
If not (if that does not work) what I would do/suggest is:
When mouse enters the top div activate a setTimeout polling functiion or .mouseMove that runs every 1 second or so which checks the mouse position and hide the top div.
If the mouse is not on the bottom div (mousemove) , then display the top div and disable the polling.
You can seach this forum for how to write a setTimeout polling function, etc. If I have some time over the weekend I will give it a whirl...
Trust this helps.
You can set the css visibility property to hidden and visible on mouseenter and mouseleave. I put some space between two divs to make the effect visible clearly.
$(document).ready(function() {
$('.dimmer').on('mouseenter', () => {
$('.dimmer').css("visibility","hidden");
}).on('mouseleave', () => {
$('.dimmer').css("visibility","visible");
});
});
.experience {
background: red;
height: 110px;
width: 110px;
z-index: 0;
}
.dimmer {
background: blue;
position: absolute;
top: -10px;
height: 110px;
width: 110px;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="experience"></div>
<div class="dimmer"></div>
</div>
jQuery(document).ready(function(){
jQuery(".dimmer").on({
mouseenter: function () {
jQuery(this).css('opacity', '0');
},
mouseleave: function () {
jQuery(this).css('opacity', '1');
}
});
});
.experience {
background: url("http://lorempixel.com/400/200/") no-repeat center;
height: 110px;
width: 110px;
z-index: 2;
}
.imparant{
position:relative;
height: 110px;
width: 110px;
}
.dimmer {
background: rgba(238, 238, 238, .25);
position: absolute;
top: 0;
left:0;
right:0;
bottom:0;
z-index: 3;
transition:opacity 320ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="imparant">
<div class="experience"></div>
<div class="dimmer"></div>
</div>
You don't really need to use jQuery or javascript at all for this. You can do it with a single div, a pseudo-element, and a hover style:
.container{
position:relative;
height: 110px;
width: 110px;
background-image: url("https://randomuser.me/api/portraits/men/41.jpg");
}
.container::before{
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
transition: opacity 0.4s;
}
.container:hover::before{
opacity: 0;
}
<div class="container"></div>
If for some reason you wanted to keep the extra divs you could still do it but you'd want to change the CSS hover rule slightly. If you were ok moving the .dimmer before .experience you could just do the hover directly on the .dimmer element:
.dimmer:hover { opacity: 0 }
Otherwise you'd need to use a descendant selector:
.outerDiv:hover .dimmer { opacity: 0 }
If you see the code sample I have shared, you can see the overlay going outside the box. I traced the issue down to the transition attribute.
I want to remove the content outside of the div. Overflow isn't working as it is supposed to. (removing transition works, but I would like to keep it if possible)
Any help is appreciated
Codepen Link
CODE
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Actually it is the border-radius that is not getting respected when the transition is happening. This is because of creation of compositing layers for accelerated rendering and can be explained by having a look at the following articles:
HTML5 Rocks - Accelerated Rendering in Chrome
GPU Accelerated Compositing in Chrome.
Why does the issue not happen when transition is disabled?
When styles change but none of the criteria that necessitates the creation of a compositing layer is satisfied (that is, no animation or transition or 3D transform etc):
There is no compositing layer and so the whole area seems to get repainted at every change. Since a full repaint happens there is no issue.
View the below snippet (in full screen mode) after enabling "Show paint rects" and "Show composited layer borders" from Dev tools and observe the following:
No areas with an orange border (compositing layer) are created.
Every time the styles are modified by setting the focus on one of the a tags, the whole area gets repainted (a red or green blinking area).
.outer {
position: relative;
height: 100px;
width: 100px;
margin-top: 50px;
border: 1px solid red;
overflow: hidden;
}
.border-radius {
border-radius: 50px;
}
.inner {
width: 50px;
height: 50px;
background-color: gray;
opacity: 0.75;
}
a:focus + .outer.border-radius > .inner {
transform: translateX(50px);
height: 51px;
opacity: 0.5;
}
<a href='#'>Test</a>
<div class='outer border-radius'>
<div class='inner'>I am a strange root.
</div>
</div>
Why does adding a transition create a problem?
Initial rendering has no compositing layer because there is no transition yet on the element. View the below snippet and note how when the snippet is run a paint (red or green blinking area) happens but no compositing layer (area with orange border) is created.
When transition starts, Chrome splits them into different compositing layers when some properties like opacity, transform etc are being transitioned. Notice how two areas with orange borders are displayed as soon as the focus is set on one of the anchor tags. These are the compositing layers that got created.
The layer splitting is happening for accelerated rendering. As mentioned in the HTML5 Rocks article, the opacity and transform changes are applied by changing the attributes of the compositing layer and no repainting occurs.
At the end of the transition, a repaint happens to merge all the layers back into a single layer because compositing layers are no longer applicable (based on criteria for creation of layers).
.outer {
position: relative;
height: 100px;
width: 100px;
margin-top: 50px;
border: 1px solid red;
overflow: hidden;
}
.border-radius {
border-radius: 50px;
}
.inner {
width: 50px;
height: 50px;
background-color: gray;
transition: all 1s 5s;
/*transition: height 1s 5s; /* uncomment this to see how other properties don't create a compositing layer */
opacity: 0.75;
}
a:focus + .outer.border-radius > .inner {
transform: translateX(50px);
opacity: 0.5;
/*height: 60px; */
}
<a href='#'>Test</a>
<div class='outer border-radius'>
<div class='inner'>I am a strange root.
</div>
</div>
This illustrates that when the layers are merged back and full repaint happens, the border-radius on the parent also gets applied and respected. However, during transition only the compositing layer's properties are changed, so the layer seems to become unaware of the properties of other layers and thus doesn't respect the border-radius of the parent.
I would assume this to be because of the way rendering of layers work. Each layer is a software bitmap and so it kind of becomes equivalent to having a circular image and then placing a div on top of it. That would obviously not result in any clipping of content.
The comment in this bug thread also seems to confirm that a repaint happens when a separate layer is no longer required.
We want to repaint if "gets own layer" is going to change
Note: Though they are Chrome specific, I think the behavior should be similar in others also.
What is the solution?
The solution seems to be to create a separate stacking context for the parent (.qs-timer) element. Creating a separate stacking context seems to result in a separate compositing layer being created for the parent and this solves the issue.
As mentioned by BoltClock in this answer, any one of the following options would create a separate stacking context for the parent and doing one of them seems to resolve the issue.
Setting a z-index on the parent .qs-timer to anything other than auto.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
z-index: 1; /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Setting opacity to anything less than 1. I have used 0.99 in the below snippet as it doesn't cause any visual difference.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
opacity: 0.99; /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Adding a transform to the element. I have used translateZ(0px) in the below snippet as this also doesn't create any visual difference.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
transform: translateZ(0px) /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
The first two approaches are more preferable than the third because the third one works only on a browser that supports CSS transforms.
Yes, adding opacity: 0.99; to .qs-timer issue will fixed.
When opacity: 1 OR NOT define:
In this special case, there is no transparency involved so that gfx could avoid doing the expensive things.
In case Opacity: 0.99:
nsIFrame::HasOpacity() decides that there is an opacity, so gfx include valuable things. ( likes opacity with border-radius)
For more help Special case opacity:0.99 to treat it as opacity:1 for graphics , This ticket is not providing the opinion of our actual goal, but giving the idea about what is happening inside of CSS.
I want to have a sliding switch. On the left would be Off and on the right would be On. When the user toggles the switch, I want the 'slider' portion to slide to the other side and indicate it is off. I could then have a callback that takes as input the state of the toggle switch so I can act accordingly.
Any idea how to do this?
check out this generator: On/Off FlipSwitch
you can get various different style outcomes and its css only - no javascript!
You mean something like IPhone checkboxes?
Try Thomas Reynolds' iOS Checkboxes script:
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() {
$(':checkbox').iphoneStyle();
});
Results:
Using plain javascript
<html>
<head>
<!-- define on/off styles -->
<style type="text/css">
.on { background:blue; }
.off { background:red; }
</style>
<!-- define the toggle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
} else {
item.className="on";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />
</body>
</html>
Using jQuery
If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:
$(document).ready(function(){
$('a#myButton').click(function(){
$(this).toggleClass("btnClicked");
});
});
Using jQuery UI effects, you can animate transitions: http://jqueryui.com/demos/toggleClass/
Initial answer from 2013
If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.
It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.
Source code is available on Github.
Note from 2018
I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.
Please consider having a look at modern Switches like those.
You can achieve this using HTML and CSS and convert a checkbox into a HTML Switch.
input.cmn-toggle-round + label {
padding: 2px;
width: 100px;
height: 30px;
background-color: #dddddd;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
}
input.cmn-toggle-round + label:before, input.cmn-toggle-round + label:after {
display: block;
position: absolute;
top: 1px;
left: 1px;
bottom: 1px;
content: "";
}
input.cmn-toggle-round + label:before {
right: 1px;
background-color: #f1f1f1;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
-webkit-transition: background 0.4s;
-moz-transition: background 0.4s;
-o-transition: background 0.4s;
transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
width: 40px;
background-color: #fff;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
-o-border-radius: 100%;
border-radius: 100%;
-webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-webkit-transition: margin 0.4s;
-moz-transition: margin 0.4s;
-o-transition: margin 0.4s;
transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
margin-left: 60px;
}
.cmn-toggle {
position: absolute;
margin-left: -9999px;
visibility: hidden;
}
.cmn-toggle + label {
display: block;
position: relative;
cursor: pointer;
outline: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div class="switch">
<input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round" type="checkbox">
<label for="cmn-toggle-1"></label>
</div>
Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:
<style type="text/css">
.toggleSwitch {
width: ...;
height: ...;
/* add other styling as appropriate to position element */
position: relative;
}
.slider {
background-image: url(...);
position: absolute;
width: ...;
height: ...;
}
.slider.on {
right: 0;
}
.slider.off {
left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
var oldRE = RegExp('\\b'+oldClass+'\\b');
elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
var onRE = RegExp('\\b'+on+'\\b');
if (onRE.test(elt.className)) {
elt.className = elt.className.replace(onRE, off);
} else {
replaceClass(elt, off, on);
}
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>
Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.
You can take a look at Shield UI's Switch widget. It is as easy to use as this:
<input id="switch3" type="checkbox" value="" />
<script>
jQuery(function ($) {
$("#switch3").shieldSwitch({
onText: "Yes, save it",
ffText: "No, delete it",
cls: "large"
});
});
</script>