JavaScript alert box with timer - javascript

I want to display the alert box but for a certain interval. Is it possible in JavaScript?

If you want an alert to appear after a certain about time, you can use this code:
setTimeout(function() { alert("my message"); }, time);
If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm or prompt is shown.
If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.
var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);

May be it's too late but the following code works fine
document.getElementById('alrt').innerHTML='<b>Please wait, Your download will start soon!!!</b>';
setTimeout(function() {document.getElementById('alrt').innerHTML='';},5000);
<div id='alrt' style="fontWeight = 'bold'"></div>

setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds

In short, the answer is no. Once you show an alert, confirm, or prompt the script no longer has control until the user returns control by clicking one of the buttons.
To do what you want, you will want to use DOM elements like a div and show, then hide it after a specified time. If you need to be modal (takes over the page, allowing no further action) you will have to do additional work.
You could of course use one of the many "dialog" libraries out there. One that comes to mind right away is the jQuery UI Dialog widget

I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.
I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.
This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.
This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.
The statements above are valid ones.... (Please allow).
How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.
CSS menus/DHTML use mouseover(valid statement).
I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.
The Prakash script above I feel could be the answer if you can adapt it.
Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.
1.
<html>
<head>
<title></title>
<script language="JavaScript">
// Variables
leftposition=screen.width-350
strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
strfiller1=' This alert is a timed one.'+'<br><br><br></td></tr></table>'
temp=strfiller0+strfiller1
// Javascript
// This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am
function preview(){
preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
preWindow.document.open();
preWindow.document.write(temp);
preWindow.document.close();
setTimeout(function(){preWindow.close()},4000);
}
</script>
</head>
<body>
<input type="button" value=" Open " onclick="preview()">
</body>
</html>
2.
<style>
body {
font-family: Arial, sans-serif;
background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
background-size: cover;
height: 100vh;
}
h1 {
text-align: center;
font-family: Tahoma, Arial, sans-serif;
color: #06D85F;
margin: 80px 0;
}
.box {
width: 40%;
margin: 0 auto;
background: rgba(255,255,255,0.2);
padding: 35px;
border: 2px solid #fff;
border-radius: 20px/50px;
background-clip: padding-box;
text-align: center;
}
.button {
font-size: 1em;
padding: 10px;
color: #fff;
border: 2px solid #06D85F;
border-radius: 20px/50px;
text-decoration: none;
cursor: pointer;
transition: all 0.3s ease-out;
}
.button:hover {
background: #06D85F;
}
.overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
transition: opacity 500ms;
visibility: hidden;
opacity: 0;
}
.overlay:target {
visibility: visible;
opacity: 1;
}
.popup {
margin: 70px auto;
padding: 20px;
background: #fff;
border-radius: 5px;
width: 30%;
position: relative;
transition: all 5s ease-in-out;
}
.popup h2 {
margin-top: 0;
color: #333;
font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.popup .close:hover {
color: #06D85F;
}
.popup .content {
max-height: 30%;
overflow: auto;
}
#media screen and (max-width: 700px){
.box{
width: 70%;
}
.popup{
width: 70%;
}
}
</style>
<script>
// written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Here i am</h2>
<a class="close" href="#">×</a>
<div class="content">
Thank to pop me out of that button, but now i'm done so you can close this window.
</div>
</div>
</div>
</body>
3.
<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers
function displayMenu(currentPosition,nextPosition) {
// Get the menu object located at the currentPosition on the screen
var whichMenu = document.getElementById(currentPosition).style;
if (displayMenu.arguments.length == 1) {
// Only one argument was sent in, so we need to
// figure out the value for "nextPosition"
if (parseInt(whichMenu.top) == -5) {
// Only two values are possible: one for mouseover
// (-5) and one for mouseout (-90). So we want
// to toggle from the existing position to the
// other position: i.e., if the position is -5,
// set nextPosition to -90...
nextPosition = -90;
}
else {
// Otherwise, set nextPosition to -5
nextPosition = -5;
}
}
// Redisplay the menu using the value of "nextPosition"
whichMenu.top = nextPosition + "px";
}
// End hiding-->
</SCRIPT>
<STYLE TYPE="text/css">
<!--
.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}
-->
</STYLE>
</HEAD>
<BODY BGCOLOR="white">
<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
Alert:<br>
<br>
You pushed that button again... Didn't yeah? <br>
<br>
<br>
<br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>

Pure HTML + CSS 5 seconds alert box using the details element toggling.
details > p {
padding: 1rem;
margin: 0
}
details[open] {
visibility: hidden;
position: fixed;
width: 33%;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
transform-origin: center center;
outline: 10000px #000000d4 solid;
animation: alertBox 5s;
border: 15px yellow solid
}
details[open] summary::after {
content: '❌';
float: right
}
#keyframes alertBox {
0% { visibility: unset}
100% { visibility: hidden }
}
<details>
<summary>Show the box 5s</summary>
<p>HTML and CSS popup with 5s tempo.</p>
<p><b>Powered by HTML</b></p>
</details>
Nb: the visibility stay hidden at closure, haven't found a way to restore it from CSS, we might have to use js to toggle a class to show it again. If someone find a way with only CSS, please edit this post!!

If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.

tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.

by using this code you can set the timer on the alert box , and it will pop up after 10 seconds.
setTimeout(function(){
alert("after 10 sec i will start");
},10000);

You can now use the HTMLDialogElement.
In this example a dialog is created when you click the button, and a timeout function is created to close it:
async function showMessage(message) {
const dialog = document.createElement("dialog");
document.body.appendChild(dialog);
dialog.innerText = message;
dialog.show();
setTimeout(function () {
dialog.close();
}, 1000);
}
<button class="btn" onclick="showMessage('This is my message')">click me!</button>
If you want you can test it on codepen.

function alertWithTimeout(title,message,timeout){
var dialog = $("<div id='dialog-confirm' title='"+title+"'>"+message+"</div>").dialog();
setTimeout(function() { dialog.dialog('close'); }, timeout);
}
alertWithTimeout("Error","This is the message" ,5000);

Related

How do I set the active state for image buttons instead of just focused state with my current code?

First time posting here and new to programming with just 3 days of experience.
I'm having some trouble getting my default button to be active instead of just focused. I've attempted to read other posts about this, but my lack of experience makes it hard for me to put 2 and 2 together.
The page is going into squarespace so I'm trying to do it all in one code block. I don't want the buttons to deactivate when the user clicks on other parts of the website, which it currently happens. (Even if they click on blank areas).
Thank you very much for any advice you can give me.
/* Change Button Size/Border/BG Color And Align To Middle */
.services {
width: 210px;
height: 135px;
padding: 0px;
border: 0px;
outline: 0px;
cursor: pointer;
color: #999999;
font-size: 20px;
text-align: center;
background: url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat;
/* As all link share the same background-image */
}
/* Set Mouseover Button Text and Current/Active Color */
.services:focus,
.services:hover,
.services:active {
color: black;
}
/* Position Button Text*/
divtext {
position: relative;
top: 90px;
}
/* Div Wrapper to format button areas. */
.servicesbuttonwrapper {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
/* Div Wrapper to format revealed description text. */
.servicestextwrapper {
text-align: left;
margin-left: 100px;
margin-right: 32px;
top: 50px;
position: relative;
}
/* Change Image rollover position depending On Focus. */
.assets {
background-position: 0 0;
}
.assets:focus,
.assets:hover,
.assets:active {
background-position: 0 -135px;
}
.viz {
background-position: 0 -270px;
}
.viz:focus,
.viz:hover,
.viz:active {
background-position: 0 -405px;
}
.software {
background-position: 0 -540px;
}
.software:focus,
.software:hover,
.software:active {
background-position: 0 -675px;
}
.more {
background-position: 0 -810px;
}
.more:focus,
.more:hover,
.more:active {
background-position: 0 -945px;
}
/* Hides intitial button descriptions. */
#assets,
#viz,
#software,
#more {
display: none;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>
<body>
<!--Div wrapper so we can format positioning of buttons in CSS-->
<div class="servicesbuttonwrapper">
<!--Base buttons plus javascript functions for click behavior. This used to be <button class> instead of <a href> but I read somewhere this is better... seems to work ok.-->
<a href="javascript:void(0)" id="defaultstate" onclick="show('software');" class="services software">
<divtext>INTERACTIVE SOFTWARE</divtext>
</a>
<a href="javascript:void(0)" onclick="show('assets');" class="services assets">
<divtext>3D ASSET CREATION</divtext>
</a>
<a href="javascript:void(0)" onclick="show('viz');" class="services viz">
<divtext>3D VISUALIZATION</divtext>
</a>
<a href="javascript:void(0)" onclick="show('more');" class="services more">
<divtext>IMAGE CREATION</divtext>
</a>
</div>
<!--Base description text.-->
<div class="servicestextwrapper">
<div id="assets">3D Assets Description.</div>
<div id="viz">3D Visualization Description.</div>
<div id="software">Interactive Software Description.</div>
<div id="more">And More Description.</div>
</div>
<!--Javascript function to hide/show elements based on button press.-->
<script type="text/javascript">
function show(elementId) {
document.getElementById("assets").style.display = "none";
document.getElementById("viz").style.display = "none";
document.getElementById("software").style.display = "none";
document.getElementById("more").style.display = "none";
document.getElementById(elementId).style.display = "block";
}
</script>
<!--Javascript function to set first button as focus.-->
<script>
window.onload = function() {
document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();
</script>
</body>
</html>
Welcome to Stack Overflow.
So first thing to note, the :active pseudo element only applies when the user clicks (mouse-down) on something. You can see it here
The most common method is to apply the css class "active", and have a .active selector on whatever element you want to style.
Right now you have the buttons affected by hover and focus, so when the user clicks outside the button it loses focus.
You can solve this by changing a bit of CSS and javascript. The edited portions are marked by /* EDIT */
I would not recommend the last line where I exploit the fact that your function passes in the element ID, and that element ID matches the class of the button that was used to select it. A better way would to have show take the Javascript event as argument, then use the event.target to get the a tag clicked on, then use a getElementById on something like a data-target="more" attribute. This will allow you to change the CSS class without coupling the class to the implementation of the Javascript
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>
<style>/* Change Button Size/Border/BG Color And Align To Middle */
.services {
width:210px;
height:135px;
padding: 0px;
border:0px;
outline:0px;
cursor: pointer;
color: #999999;
font-size: 20px;
text-align: center;
background: url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat; /* As all link share the same background-image */
}
/* Set Mouseover Button Text and Current/Active Color */
/* EDIT */
.services:focus, .services:hover, .services.active {
color: black;
}
/* Position Button Text*/
divtext {
position: relative;
top: 90px;
}
/* Div Wrapper to format button areas. */
.servicesbuttonwrapper {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
/* Div Wrapper to format revealed description text. */
.servicestextwrapper {
text-align: left;
margin-left: 100px;
margin-right: 32px;
top: 50px;
position: relative;
}
/* Change Image rollover position depending On Focus. */
.assets {
background-position: 0 0;
}
/* EDIT */
.assets:focus, .assets:hover, .assets.active {
background-position: 0 -135px;
}
.viz {
background-position: 0 -270px;
}
/* EDIT */
.viz:focus, .viz:hover, .viz.active {
background-position: 0 -405px;
}
.software {
background-position: 0 -540px;
}
/* EDIT */
.software:focus, .software:hover, .software.active {
background-position: 0 -675px;
}
.more {
background-position: 0 -810px;
}
/* EDIT */
.more:focus, .more:hover, .more.active {
background-position: 0 -945px;
}
/* Hides intitial button descriptions. */
#assets, #viz, #software, #more {
display: none;
}
</style>
<body>
<!--Div wrapper so we can format positioning of buttons in CSS-->
<div class="servicesbuttonwrapper">
<!--Base buttons plus javascript functions for click behavior. This used to be <button class> instead of <a href> but I read somewhere this is better... seems to work ok.-->
<divtext>INTERACTIVE SOFTWARE</divtext>
<divtext>3D ASSET CREATION</divtext>
<divtext>3D VISUALIZATION</divtext>
<divtext>IMAGE CREATION</divtext>
</div>
<!--Base description text.-->
<div class="servicestextwrapper">
<div id="assets">3D Assets Description.</div>
<div id="viz">3D Visualization Description.</div>
<div id="software">Interactive Software Description.</div>
<div id="more">And More Description.</div>
</div>
<!--Javascript function to hide/show elements based on button press.-->
<script type="text/javascript">
/* EDIT */
function show(elementId) {
document.getElementById("assets").style.display = "none";
document.getElementById("viz").style.display = "none";
document.getElementById("software").style.display = "none";
document.getElementById("more").style.display = "none";
document.getElementById(elementId).style.display = "block";
// get a list of the buttons with ".services" class
const buttons = document.querySelectorAll(".services");
for(let button of buttons) {
// remove ".active" class
button.classList.remove("active");
}
// add the active class to element button specified by argument
document.querySelector("." + elementId).classList.add("active");
}
</script>
<!--Javascript function to set first button as focus.-->
<script>
window.onload=function(){
document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();
</script>
</body>
</html>

Forcing mobile devices to activate :hover CSS properties on first touch and activate link on second touch

: )
So, I'm trying to solve a hover effect issue. I have tooltips on some of my links. Code looks like this:
<a href="https://wikipedia.org/wiki/Space_Shuttle_Atlantis">
<h6 class="has-tip">Space Shuttle
<p class="tip">The space shuttle was invented by Santa Claus</p>
</h6>
</a>
And the CSS is a bit more involved:
.tip {
display: block;
position: absolute;
bottom: 100%;
left: 0;
width: 100%;
pointer-events: none;
padding: 20px;
margin-bottom: 15px;
color: #fff;
opacity: 0;
background: rgba(255,255,255,.8);
color: coal;
font-family: 'Ubuntu Light';
font-size: 1em;
font-weight: normal;
text-align: left;
text-shadow: none;
border-radius: .2em;
transform: translateY(10px);
transition: all .25s ease-out;
box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
}
.tip::before {
content: " ";
display: block;
position: absolute;
bottom: -20px;
left: 0;
height: 20px;
width: 100%;
}
.tip::after { /* the lil triangle */
content: " ";
position: absolute;
bottom: -10px;
left: 50%;
height: 0;
width: 0;
margin-left: -13px;
border-left: solid transparent 10px;
border-right: solid transparent 10px;
border-top: solid rgba(255,255,255,.8) 10px;
}
.has-tip:hover .tip {
opacity 1;
pointer-events auto;
transform translateY(0px);
}
Now, on desktop this works wonderfully. You hover over the tiny title and you get a pretty looking tooltip, then if you click anywhere on the title or tooltip (unless you decide to put yet another link in the paragraph which works separately and nicely) you activate the link. Yay : )
Now on mobile, the whole thing gets funky. Touching just activates the link. If you have slow internet, or iOS, you might glimpse the tooltip just as the next page loads.
I would like the following behavior:
User taps on tiny title (h6) which has class (has-tip)
If this is the first tap, the tooltip shows, and nothing else happens. 3)
If the tooltip is already showing when they tap (as in a subsequent
tap) then the link is activate and the new page loads.
Any ideas how I might implement this? No jQuery if possible.
One way to do it is to save a reference to the last clicked has-tip link and to apply a class to it which forces the tip to show. When you click on a link and it matches the the last one clicked, you let the event pass.
EDIT: oh, I forgot to mention you might need a classList shim for old IE.
JSFiddle link.
HTML
<a href="http://jsfiddle.net/1tc52muq/5/" class="has-tip">
JSFiddle<span class="tip">Click for some fun recursion</span>
</a><br />
<a href="http://google.com" class="has-tip">
Google<span class="tip">Click to look for answers</span>
</a>
JS
lastTip = null;
if(mobile) {
var withtip = document.querySelectorAll(".has-tip");
for(var i=0; i<withtip.length; ++i) {
withtip[i].addEventListener("click", function(e) {
if(lastTip != e.target) {
e.preventDefault();
if(lastTip) lastTip.classList.remove("force-tip");
lastTip = e.target;
lastTip.classList.add("force-tip");
}
});
}
}
CSS
.has-tip {
position: abolute;
}
.tip {
display: none;
position: relative;
left: 20px;
background: black;
color: white;
}
.has-tip:hover .tip, .force-tip .tip {
display: inline-block;
}
Edit: Just wanted to say that Jacques' approach is similar, but much more elegant.
On touch devices, you'll need to make a click/tap counter:
1) On first tap of any link, store the link and display the hover state.
2) On another tap, check to see if it's the same as the first, and then perform the normal tap action if it is. Otherwise, clear any existing hovers, and set the new tap target as the one to count.
3) Reset / clear any hovers if you tap on non-links.
I've made a rudimentary JSFiddle that console.logs these actions. Since we're not using jQuery, I didn't bother with adding/removing CSS classes on the elements.
Also, sorry about not writing taps instead of clicks.
var clickTarget;
var touchDevice = true;
if(touchDevice) {
var links = document.getElementsByTagName('a');
for(var i=0; i<links.length; i++) {
links[i].onclick = function(event) {
event.stopPropagation();
event.preventDefault(); // this is key to ignore the first tap
checkClick(event);
};
};
document.onclick = function() {
clearClicks();
};
}
var checkClick = function(event) {
if(clickTarget === event.target) {
// since we're prevent default, we need to manually trigger an action here.
console.log("Show click state and also perform normal click action.");
clearClicks();
} else {
console.log("New link clicked / Show hover");
clickTarget = event.target;
}
}
var clearClicks = function() {
console.log("Clearing clicks");
clickTarget = undefined;
};
http://jsfiddle.net/doydLt6v/1/

Blog / Message - How do I fix that empty message divs will piling on / next to each other and make the close button work?

So I'm making a sort of blog posting system or TODO list, however you want to call it.
I want that the following can happen / is possible:
[Working] The user types something in the textarea
[Working] The user clicks on the button.
[Working] A new div will be created with the text of the textarea.
[Working] The textarea will be empty.
[Not Working] The user has got the choice to delete the post by clicking the 'X' on the right side of each '.post' div.
BUT: If I click on the button when there's nothing in the textarea, there appears an empty div, with only an 'X' close button, no background color either. They appear on the same line as the previous message, so you can get a lot of 'X's next to each other.
AND: Clicking the 'X' close button doesn't do anything. No errors in Firefox console.
If it's not clear enough, run this JSFiddle, click the button and I think you'll understand what I mean:
JSFiddle
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div id="blog">
<h1>Blog post application</h1>
<div id="post-system">
<textarea id="poster" rows="5" cols="50" placeholder="Update status."></textarea>
<div id="button">Post</div>
<div id="posts">
</div>
</div>
</div>
</body>
</html>
jQuery Script:
<script>
$(document).ready(function () {
$('#button').click(function () {
var text = $('#poster').val();
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('.close-post').click(function () {
('.close-post').parent().hide();
});
});
</script>
CSS:
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
#blog {
background-color: blue;
margin: 50px;
padding: 50px;
text-align: center;
border-radius: 10px;
color: white;
display: block;
}
#poster {
color: default;
resize: none;
border: 1px solid black;
text-decoration: blink;
font-size: 20px;
display: inline-block;
position: relative;
border-radius: 5px;
border: 2px solid black;
padding-left: 10px;
padding-top: 5px;
}
#button {
background-color: #00FFFF;
color: white;
border: 2px solid white;
border-radius: 5px;
cursor: pointer;
width: 50px;
float: left;
}
.post {
background-color: white;
color: blue;
margin-top: 20px;
width: auto;
display: block;
}
.close-post {
margin-right: 10px;
float: right;
color: red;
cursor: pointer;
}
You appear to have two issues:
1) You don't want a post to be created if the textarea is empty
Simple fix . . . check to see if it is empty, before calling the logic to add the new post (and use jQuery's $.trim() to account for only blank spaces):
$('#button').click(function() {
var text = $.trim($('#poster').val());
if (text !== "") {
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
}
});
2) The 'X' buttons are not closing the posts
This also should be a pretty easy fix . . . the reason that they are not working is because the 'X' buttons don't exist when the page is loaded so $('.close-post').click(function() { is not binding to them on page load. You will need to delegate that event binding, so that it will apply to the 'X' buttons that are dynamically added after the page is loaded.
Now, not knowing what version of jQuery that you are using (I can't access jsFiddle from work), I'll point you to the right place to figure out the correct way to do it: https://api.jquery.com/on/
If it is jQuery 1.7 or higher, you would do it like this:
$("#posts").on("click", ".close-post", function() {
$(this).parent().hide();
});
If your version is earlier than that, then investigate the jQuery .delegate() and .live() methods to determine which is the right one to use for your code..
Try this:
$(document).ready(function() {
$('#button').click(function(event) {
event.preventDefault();
var text= $('#poster').val();
if (text === '') {
alert('Nothing to post!');
return;
}
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('#posts').on('click', '.close-post', function() {
$(this).closest('.post').fadeOut();
});
});
JSFiddle
The way you are doing this, the user will only ever see what they are posting - if you're trying for a chat type where users talk to each other then you will need to store what is being typed on the server side and refresh the screen using something like ajax
but in response to your question, you need to bind the close click like this:
$( "#posts" ).on( "click", ".close-post", function() {
$(this).parent().hide(); // $(this) is the clicked icon, the way you did it above wouldn't as if it had the dollar, it would close all .close-post parents
});
See the part about delegated events: http://api.jquery.com/on/

ReCaptcha API v2 Styling

I have not had much success finding how to style Google's new recaptcha (v2). The eventual goal is to make it responsive, but I am having difficulty applying styling for even simple things like width.
Their API documentation does not appear to give any specifics on how to control styling at all other than the theme parameter, and simple CSS & JavaScript solutions haven't worked for me.
Basically, I need to be able to apply CSS to Google's new version of reCaptcha. Using JavaScript with it is acceptable.
Overview:
Sorry to be the answerer of bad news, but after research and debugging, it's pretty clear that there is no way to customize the styling of the new reCAPTCHA controls. The controls are wrapped in an iframe, which prevents the use of CSS to style them, and Same-Origin Policy prevents JavaScript from accessing the contents, ruling out even a hacky solution.
Why No Customize API?:
Unlike reCAPTCHA API Version 1.0, there are no customize options in API Version 2.0. If we consider how this new API works, it's no surprise why.
Excerpt from Are you a robot? Introducing “No CAPTCHA reCAPTCHA”:
While the new reCAPTCHA API may sound simple, there is a high degree of sophistication behind that modest checkbox. CAPTCHAs have long relied on the inability of robots to solve distorted text. However, our research recently showed that today’s Artificial Intelligence technology can solve even the most difficult variant of distorted text at 99.8% accuracy. Thus distorted text, on its own, is no longer a dependable test.
To counter this, last year we developed an Advanced Risk Analysis backend for reCAPTCHA that actively considers a user’s entire engagement with the CAPTCHA—before, during, and after—to determine whether that user is a human. This enables us to rely less on typing distorted text and, in turn, offer a better experience for users. We talked about this in our Valentine’s Day post earlier this year.
If you were able to directly manipulate the styling of the control elements, you could easily interfere with the user-profiling logic that makes the new reCAPTCHA possible.
What About a Custom Theme?:
Now the new API does offer a theme option, by which you can choose a preset theme such as light and dark. However there is not presently a way to create a custom theme. If we inspect the iframe, we will find the theme name is passed in the query string of the src attribute. This URL looks something like the following.
https://www.google.com/recaptcha/api2/anchor?...&theme=dark&...
This parameter determines what CSS class name is used on the wrapper element in the iframe and determines the preset theme to use.
Digging through the minified source, I found that there are actually 4 valid theme values, which is more than the 2 listed in the documentation, but default and standard are the same as light.
We can see the code that selects the class name from this object here.
There is no code for a custom theme, and if any other theme value is specified, it will use the standard theme.
In Conclusion:
At present, there is no way to fully style the new reCAPTCHA elements, only the wrapper elements around the iframe can be stylized. This was almost-certainly done intentionally, to prevent users from breaking the user profiling logic that makes the new captcha-free checkbox possible. It is possible that Google could implement a limited custom theme API, perhaps allowing you to choose custom colors for existing elements, but I would not expect Google to implement full CSS styling.
As guys mentioned above, there is no way ATM. but still if anyone interested, then by adding in just two lines you can at least make it look reasonable, if it break on any screen. you can assign different value in #media query.
<div id="recaptchaContainer" style="transform:scale(0.8);transform-origin:0 0"></div>
Hope this helps anyone :-).
I use below trick to make it responsive and remove borders. this tricks maybe hide recaptcha message/error.
This style is for rtl lang but you can change it easy.
.g-recaptcha {
position: relative;
width: 100%;
background: #f9f9f9;
overflow: hidden;
}
.g-recaptcha > * {
float: right;
right: 0;
margin: -2px -2px -10px;/*remove borders*/
}
.g-recaptcha::after{
display: block;
content: "";
position: absolute;
left:0;
right:150px;
top: 0;
bottom:0;
background-color: #f9f9f9;
clear: both;
}
<div class="g-recaptcha" data-sitekey="Your Api Key"></div>
<script src='https://www.google.com/recaptcha/api.js?hl=fa'></script>
Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:
Click here to preview
.g-recaptcha-outer{
text-align: center;
border-radius: 2px;
background: #f9f9f9;
border-style: solid;
border-color: #37474f;
border-width: 1px;
border-bottom-width: 2px;
}
.g-recaptcha-inner{
width: 154px;
height: 82px;
overflow: hidden;
margin: 0 auto;
}
.g-recaptcha{
position:relative;
left: -2px;
top: -1px;
}
<div class="g-recaptcha-outer">
<div class="g-recaptcha-inner">
<div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
</div>
</div>
Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.
Refer: google recaptcha docs
What you can do is to hide the ReCaptcha Control behind a div. Then make your styling on this div. And set the css "pointer-events: none" on it, so you can click through the div (Click through a DIV to underlying elements).
The checkbox should be in a place where the user is clicking.
You can recreate recaptcha , wrap it in a container and only let the checkbox visible. My main problem was that I couldn't take the full width so now it expands to the container width. The only problem is the expiration you can see a flick but as soon it happens I reset it.
See this demo http://codepen.io/alejandrolechuga/pen/YpmOJX
function recaptchaReady () {
grecaptcha.render('myrecaptcha', {
'sitekey': '6Lc7JBAUAAAAANrF3CJaIjt7T9IEFSmd85Qpc4gj',
'expired-callback': function () {
grecaptcha.reset();
console.log('recatpcha');
}
});
}
.recaptcha-wrapper {
height: 70px;
overflow: hidden;
background-color: #F9F9F9;
border-radius: 3px;
box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
-webkit-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
-moz-box-shadow: 0px 0px 4px 1px rgba(0,0,0,0.08);
height: 70px;
position: relative;
margin-top: 17px;
border: 1px solid #d3d3d3;
color: #000;
}
.recaptcha-info {
background-size: 32px;
height: 32px;
margin: 0 13px 0 13px;
position: absolute;
right: 8px;
top: 9px;
width: 32px;
background-image: url(https://www.gstatic.com/recaptcha/api2/logo_48.png);
background-repeat: no-repeat;
}
.rc-anchor-logo-text {
color: #9b9b9b;
cursor: default;
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 10px;
font-weight: 400;
line-height: 10px;
margin-top: 5px;
text-align: center;
position: absolute;
right: 10px;
top: 37px;
}
.rc-anchor-checkbox-label {
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 14px;
font-weight: 400;
line-height: 17px;
left: 50px;
top: 26px;
position: absolute;
color: black;
}
.rc-anchor .rc-anchor-normal .rc-anchor-light {
border: none;
}
.rc-anchor-pt {
color: #9b9b9b;
font-family: Roboto,helvetica,arial,sans-serif;
font-size: 8px;
font-weight: 400;
right: 10px;
top: 53px;
position: absolute;
a:link {
color: #9b9b9b;
text-decoration: none;
}
}
g-recaptcha {
// transform:scale(0.95);
// -webkit-transform:scale(0.95);
// transform-origin:0 0;
// -webkit-transform-origin:0 0;
}
.g-recaptcha {
width: 41px;
/* border: 1px solid red; */
height: 38px;
overflow: hidden;
float: left;
margin-top: 16px;
margin-left: 6px;
> div {
width: 46px;
height: 30px;
background-color: #F9F9F9;
overflow: hidden;
border: 1px solid red;
transform: translate3d(-8px, -19px, 0px);
}
div {
border: 0;
}
}
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaReady&&render=explicit'></script>
<div class="recaptcha-wrapper">
<div id="myrecaptcha" class="g-recaptcha"></div>
<div class="rc-anchor-checkbox-label">I'm not a Robot.</div>
<div class="recaptcha-info"></div>
<div class="rc-anchor-logo-text">reCAPTCHA</div>
<div class="rc-anchor-pt">
Privacy
<span aria-hidden="true" role="presentation"> - </span>
Terms
</div>
</div>
Great!
Now here is styling available for reCaptcha..
I just use inline styling like:
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXX" style="transform: scale(1.08); margin-left: 14px;"></div>
whatever you wanna to do small customize in inline styling...
Hope it will help you!!
I came across this answer trying to style the ReCaptcha v2 for a site that has a light and a dark mode. Played around some more and discovered that besides transform, filter is also applied to iframe elements so ended up using the default/light ReCaptcha and doing this when the user is in dark mode:
.g-recaptcha {
filter: invert(1) hue-rotate(180deg);
}
The hue-rotate(180deg) makes it so that the logo is still blue and the check-mark is still green when the user clicks it, while keeping white invert()'ed to black and vice versa.
Didn't see this in any answer or comment so decided to share even if this is an old thread.
Just adding a hack-ish solution to make it responsive.
Wrap the recaptcha in an extra div:
<div class="recaptcha-wrap">
<div id="g-recaptcha"></div>
</div>
Add styles. This assumes the dark theme.
// Recaptcha
.recaptcha-wrap {
position: relative;
height: 76px;
padding:1px 0 0 1px;
background:#222;
> div {
position: absolute;
bottom: 2px;
right:2px;
font-size:10px;
color:#ccc;
}
}
// Hides top border
.recaptcha-wrap:after {
content:'';
display: block;
background-color: #222;
height: 2px;
width: 100%;
top: -1px;
left: 0px;
position: absolute;
}
// Hides left border
.recaptcha-wrap:before {
content:'';
display: block;
background-color: #222;
height: 100%;
width: 2px;
top: 0;
left: -1px;
position: absolute;
z-index: 1;
}
// Makes it responsive & hides cut-off elements
#g-recaptcha {
overflow: hidden;
height: 76px;
border-right: 60px solid #222222;
border-top: 1px solid #222222;
border-bottom: 1px solid #222;
position: relative;
box-sizing: border-box;
max-width: 294px;
}
This yields the following:
It will now resize horizontally, and doesn't have a border. The recaptcha logo would get cut off on the right, so I am hiding it with a border-right. It's also hiding the privacy and terms links, so you may want to add those back in.
I attempted to set a height on the wrapper element, and then vertically center the recaptcha to reduce the height. Unfortunately, any combo of overflow:hidden and a smaller height seems to kill the iframe.
in the V2.0 it's not possible. The iframe blocks all styling out of this. It's difficult to add a custom theme instead of the dark or light one.
Late to the party, but maybe my solution will help somebody.
I haven't found any solution that works on a responsive website when the viewport changes or the layout is fluid.
So I've created a jQuery script for django-cms that is dynamically adapting to a changing viewport.
I'm going to update this response as soon as I have the need for a modern variant of it that is more modular and has no jQuery dependency.
html
<div class="g-recaptcha" data-sitekey="{site_key}" data-size={size}>
</div>
css
.g-recaptcha { display: none; }
.g-recaptcha.g-recaptcha-initted {
display: block;
overflow: hidden;
}
.g-recaptcha.g-recaptcha-initted > * {
transform-origin: top left;
}
js
window.djangoReCaptcha = {
list: [],
setup: function() {
$('.g-recaptcha').each(function() {
var $container = $(this);
var config = $container.data();
djangoReCaptcha.init($container, config);
});
$(window).on('resize orientationchange', function() {
$(djangoReCaptcha.list).each(function(idx, el) {
djangoReCaptcha.resize.apply(null, el);
});
});
},
resize: function($container, captchaSize) {
scaleFactor = ($container.width() / captchaSize.w);
$container.find('> *').css({
transform: 'scale(' + scaleFactor + ')',
height: (captchaSize.h * scaleFactor) + 'px'
});
},
init: function($container, config) {
grecaptcha.render($container.get(0), config);
var captchaSize, scaleFactor;
var $iframe = $container.find('iframe').eq(0);
$iframe.on('load', function() {
$container.addClass('g-recaptcha-initted');
captchaSize = captchaSize || { w: $iframe.width() - 2, h: $iframe.height() };
djangoReCaptcha.resize($container, captchaSize);
djangoReCaptcha.list.push([$container, captchaSize]);
});
},
lateInit: function(config) {
var $container = $('.g-recaptcha.g-recaptcha-late').eq(0).removeClass('.g-recaptcha-late');
djangoReCaptcha.init($container, config);
}
};
window.djangoReCaptchaSetup = window.djangoReCaptcha.setup;
With the integration of the invisible reCAPTCHA you can do the following:
To enable the Invisible reCAPTCHA, rather than put the parameters in a div, you can add them directly to an html button.
a. data-callback=””. This works just like the checkbox captcha, but is required for invisible.
b. data-badge: This allows you to reposition the reCAPTCHA badge (i.e. logo and
‘protected by reCAPTCHA’ text) . Valid options as ‘bottomright’ (the default),
‘bottomleft’ or ‘inline’ which will put the badge directly above the button. If you
make the badge inline, you can control the CSS of the badge directly.
In case someone struggling with the recaptcha of contact form 7 (wordpress) here is a solution working for me
.wpcf7-recaptcha{
clear: both;
float: left;
}
.wpcf7-recaptcha{
margin-right: 6px;
width: 206px;
height: 65px;
overflow: hidden;
border-right: 1px solid #D3D3D3;
}
.wpcf7-recaptcha iframe{
padding-bottom: 15px;
border-bottom: 1px solid #D3D3D3;
background: #F9F9F9;
border-left: 1px solid #d3d3d3;
}
if you use scss, that worked for me:
.recaptcha > div{
transform: scale(0.84);
transform-origin: 0;
}
If someone is still interested, there is a simple javascript library (no jQuery dependency), named custom recaptcha. It lets you customize the button with css and implement some js events (ready/checked). The idea is to make the default recaptcha "invisible" and put a button over it. Just change the id of the recaptcha and that's it.
<head>
<script src="https://azentreprise.org/download/custom-recaptcha.min.js"></script>
<style type="text/css">
#captcha {
float: left;
margin: 2%;
background-color: rgba(72, 61, 139, 0.5); /* darkslateblue with 50% opacity */
border-radius: 2px;
font-size: 1em;
color: #C0FFEE;
}
#captcha.success {
background-color: rgba(50, 205, 50, 0.5); /* limegreen with 50% opacity */
color: limegreen;
}
</style>
</head>
<body>
<div id="captcha" data-sitekey="your_site_key" data-label="Click here" data-label-spacing="15"></div>
</body>
See https://azentreprise.org/read.php?id=1 for more information.
I am just adding this kind of solution / quick fix so it won't get lost in case of a broken link.
Link to this solution "Want to add link How to resize the Google noCAPTCHA reCAPTCHA | The Geek Goddess" was provided by Vikram Singh Saini and simply outlines that you could use inline CSS to enforce framing of the iframe.
// Scale the frame using inline CSS
<div class="g-recaptcha" data-theme="light"
data-sitekey="XXXXXXXXXXXXX"
style="transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
">
</div>
// Scale the images using a stylesheet
<style>
#rc-imageselect, .g-recaptcha {
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>
You can use some CSS for Google reCAPTCHA v2 styling on your website:
– Change background, color of Google reCAPTCHA v2 widget:
.rc-anchor-light {
background: #fff!important;
color: #fff!important; }
or
.rc-anchor-normal{
background: #000 !important;
color: #000 !important; }
– Resize the Google reCAPTCHA v2 widget by using this snippet:
.rc-anchor-light {
transform:scale(0.9);
-webkit-transform:scale(0.9); }
– Responsive your Google reCAPTCHA v2:
#media only screen and (min-width: 768px) {
.rc-anchor-light {
transform:scale(0.85);
-webkit-transform:scale(0.85); }
}
All elements, property of CSS above that’s just for your reference. You can change them by yourself (only using CSS class selector).
Refer on OIW Blog - How To Edit CSS of Google reCAPTCHA (Re-style, Change Position, Resize reCAPTCHA Badge)
You can also find out Google reCAPTCHA v3's styling there.
A bit late but I tried this and it worked to make the Recaptcha responsive on screens smaller than 460px width. You can't use css selector to select elements inside the iframe. So, better use the outermost parent element which is the class g-recaptcha to basically zoom-out i.e transform the size of the entire container. Here's my code which worked:
#media(max-width:459.99px) {
.modal .g-recaptcha {
transform:scale(0.75);
-webkit-transform:scale(0.75); }
}
}
Incase someone wants to resize recaptcha for small devices.
I was using recaptcha V2 with primeng p-captcha (for angular). The issue was that for smaller screens it would go out of the screen.
Although you can't actually resize it (the external thing and all everyone has explained it above) but there is a way with transform property (scaling the the container)
this was my code below the way, I achieved it
p-captcha div div {
transform:scale(0.9) !important;
-webkit-transform:scale(0.9) !important;
transform-origin:0 0 !important;
-webkit-transform-origin:0 0 !important;
}
Other than p-captcha you can use this code snippet below
.g-recaptcha {
transform:scale(0.9);
transform-origin:0 0;
}
Before
After
Topic is old, but I also wanted to scale the reCAPTCHA widget -- but to make it bigger for phone users, unlike many others who wanted it smaller. The only way that worked was transform: scale(x), but that seemed to make the widget too wide for my page, thus shrinking the rest of the form on the page. Using a container div as shown below fixed my problem, and hopefully it will help someone else who thinks a bigger version is better on a small screen.
<style>
:root {
/* factor to scale the Google widget in potrait mode (on a phone) */
--recaptcha-scale: 2;
}
#media screen and (orientation: portrait) {
/* needed to rein in the width of inner div when it is scaled */
#g_recaptcha_div_container {
width: calc(100vmin / var(--recaptcha-scale));
}
#g_recaptcha_div {
transform: scale(var(--recaptcha-scale));
transform-origin: 0 0;
}
#submit_button {
width: 65vmin;
height: 9vmin;
font-size: 7vmin;
/* needed to scoot the button out from under the scaled div */
margin-top: 10vmin;
}
}
</style>
<html>
<!-- top of form with a bunch of fields to create an acct -->
<div id="g_recaptcha_div_container">
<div id="g_recaptcha_div" class="g-recaptcha" data-sitekey="foo">
</div>
</div>
<input id="submit_button" type="submit" value="Create Account">
<!-- bottom of form -->
</html>
You can try to color it with this css filter hack:
.colorize-pink {
filter: brightness(0.5) sepia(1) hue-rotate(-70deg) saturate(5);
}
.colorize-navy {
filter: brightness(0.2) sepia(1) hue-rotate(180deg) saturate(5);
}
and for the size, use transform css hack
.captcha-size {
transform:scale(0.8);transform-origin:0 0
}
Lets play a little with JavaScript:
First at all, we know that recaptcha badget include all the shit from the most crazy people on Google, so you can only make changes with theme "dark" and "light" on your web.
Take a look to my website
SantiagoSoñora.
let recaptcha = document.querySelector('.g-recaptcha');
With this, you only can touch simple settings of the badge, like z-index and size, but no much more...
So far, i made two functions that set data-theme to light or dark mode at innit. Note that its neccessary assign the "light" because Google not include that by default.
function reCaptchaDark() {
document.addEventListener('DOMContentLoaded', (event) => {
recaptcha.setAttribute("data-theme", "dark");
})
}
function reCaptchaLight() {
document.addEventListener('DOMContentLoaded', (event) => {
recaptcha.setAttribute("data-theme", "light");
})
}
Then, for example, my web looks if user prefers a dark or a light theme, and set that configurations to the recaptcha bag:
(theme.onLoad = function() {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
reCaptchaDark();
toggleTheme();
}
else {
reCaptchaLight();
}
})();
Note that my code for toggle from dark to light is on the toggleTheme() function.
Keep doing magic: You should configure a class on the html tag or something else on your web for made the change between dark and light theme, and with that we now modify the src on the iframe so when we toggle dark/light mode ,with our button it changes:
theme.onclick = function() {
toggleTheme();
if (html.classList.contains('dark')) {
recaptcha.setAttribute("data-theme", "dark");
setTimeout(function() {
let iframes = document.querySelectorAll('iframe');
iframes[0].src = iframes[0].src.replace('&theme=light', '&theme=dark');
}, 0);
}
else {
recaptcha.setAttribute("data-theme", "light");
setTimeout(function() {
let iframes = document.querySelectorAll('iframe');
iframes[0].src = iframes[0].src.replace('&theme=dark', '&theme=light');
}, 0);
}
}
And here you go, the recaptcha badge change from dark to light "preassigned" themes by Google bad guys.
And last but not least, a function that updates the page to change if your theme is dark by default.
This update the LocalStorage
(function() {
if( window.localStorage ) {
if( !localStorage.getItem('firstLoad') ) {
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
You can use the class .grecaptcha-badge for some css changes, like opacity and box-shadow, -> (use !important)
Thats all, hope you can implement on your site

Display value in jQueryUI ProgressBar

I've set up a simple jQuery UI ProgressBar:
<script type="text/javascript">
$(function() {
$("#progressbar").progressbar({
value: 35
});
});
</script>
<div id="progressbar"> </div>
Among other things, I'd like to display some text in the progress-bar (for starters, I'd just use the "value").
I can't seem to get this to work.
Bonus Question: How do I format the displayed text (e.g. color, alignment)?
Instead of introducing another element (span) and a new style, leverage what is already there like this:
var myPer = 35;
$("#progressbar")
.progressbar({ value: myPer })
.children('.ui-progressbar-value')
.html(myPer.toPrecision(3) + '%')
.css("display", "block");
The css("display", "block") is to handle the case where the value is 0 (jQuery UI sets a display: none on the element when the value is 0).
If you look at the source of The demo, you'll notice that a <div class="ui-progressbar-value"> is added. You can simply override this class in your own CSS, like:
.ui-progressbar-value {
font-size: 13px;
font-weight: normal;
line-height: 18px;
padding-left: 10px;
}
The way I did it was:
<div class="progressbar"><span style="position:absolute; margin-left:10px; margin-top:2px>45% or whatever text you want to put in here</span></div>
You can adjust the margin-top and margin-left so that the text is in the center of the progress bar.
Then you apply the progressbar plugin for the elements which have class progressbar in the javascript section of the page
Hope this help
After fiddling around with some solutions, based on the answers here, I've ended up with this one:
Html:
<div id="progress"><span class="caption">Loading...please wait</span></div>
JS:
$("#progress").children('span.caption').html(percentage + '%');
(To be called inside the function that updates the progressbar value)
CSS:
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
Advantages:
Caption is centered with no harcoded positioning (necessary if caption width changes dinamically)
No JS strange manipulation
Simple and minimal CSS
This solution allows for a flexible width based on the text as well as centering the text, styling the text, etc. Works in Chrome, FF, IE8, and IE8 in compatibility mode. Didn't test IE6.
Html:
<div class="progress"><span>70%</span></div>
Script:
$(".progress").each(function() {
$(this).progressbar({
value: 70
}).children("span").appendTo(this);
});
CSS:
.progress.ui-progressbar {position:relative;height:2em;}
.progress span {position:static;margin-top:-2em;text-align:center;display:block;line-height:2em;padding-left:10px;padding-right:10px;}
.progress[aria-valuenow="0"] span {margin-top:0px;}​
Working sample: http://jsfiddle.net/hasYK/
I used this:
<div id="progressbar" style="margin: 0px 0px 16px 0px; "><span style="position: absolute;text-align: center;width: 269px;margin: 7px 0 0 0; ">My %</span></div>
<style>
#progress {
height: 18px;
}
#progress .ui-progressbar {
position: relative;
}
#progress .ui-progressbar-value {
margin-top: -20px;
}
#progress span.caption {
display: block;
position: static;
text-align: center;
}
</style>
</head>
<body>
test
<div id="progressbar"></div>
<br>
test2
<div id="progressbar2"></div>
<script>
$("#progressbar").progressbar({
max : 1024,
value : 10
});
$("#progressbar2").progressbar({
value : 50
});
$(document).ready(function() {
$("#progressbar ").children('div.ui-progressbar-value').html('10');
$("#progressbar2 ").children('div.ui-progressbar-value').html('50%');
});
</script>
</body>

Categories

Resources