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
I am currently trying to have a part of the text one my website, when clicked scroll to a certain location in the website. I have this code which works, but just jumps, which takes away from the user interface.
The following is the code that I currently have:
Go to Part One!
<div id="part1">Hey Yeah!</div>
Please know that I don't code like that, It is just for the example.
Define a function as here:
function scrollToBox(element, offset) {
var destination = $(element).offset().top - (offset ? offset : 120);
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1500);
}
Then in onclick event you can call it like following code:
scrollToBox('#part1', 0);
Provided is a PLUNKER and a Snippet that uses jQuery animate(). The details are in the comments in the source.
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=0" />
<link href='https://fonts.googleapis.com/css?family=Quicksand:300' rel='stylesheet' />
<style>
/* Core~~~~~~~~~~~~~~~*/
html {
box-sizing: border-box;
font: 300 16px/1.428'Quicksand';
height: 100vh;
width: 100vw;
}
*,
*:before,
*:after {
box-sizing: inherit;
margin: 0;
padding: 0;
}
body {
position: relative;
font-size: 1rem;
line-height: 1;
height: 100vh;
width: 100vw;
overflow-x: hidden;
overflow-y: scroll;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #000;
color: #eee;
display: table;
}
h1,
h2,
h3,
h4,
h5,
h6,
legend {
font-variant: small-caps;
margin-bottom: 15px;
color: #Fc3;
text-align: center;
}
h1 {
font-size: 1.5rem;
}
h2 {
font-size: 1.4rem;
}
h3 {
font-size: 1.3rem;
}
legend {
font-size: 1.35rem;
}
p {
margin: 0 5px 15px;
}
img {
display: block;
max-width: 100%;
height: auto;
margin: 20px auto;
}
a {
color: #Fc0;
text-decoration: none;
margin: 10px 20px;
display: inline-block;
font-size: 1.5rem;
font-weight: 700;
}
a:hover {
color: #CCC;
}
header {
position: relative;
top: 0;
left: 0;
right: 0;
width: 100%;
border-bottom: 3px outset #bbb;
height: 80px;
z-index: 11;
background: #000;
text-align: center;
}
footer {
position: relative;
bottom: 0;
left: 0;
right: 0;
width: 100%;
border-top: 3px outset #bbb;
text-align: center;
height: 80px;
z-index: 11;
background: #000;
margin: 0 auto;
}
.content {
width: 100%;
height: 100%;
margin: 0 auto;
position: relative;
padding: 20px;
}
.sec {
width: 92%;
height: auto;
border: 5px ridge #999;
border-radius: 12px;
margin: 20px auto;
}
</style>
</head>
<body>
<header>
<nav id="top">To End
</nav>
</header>
<section class="sec">
<article class="content">
<iframe src='http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll' scrolling='no' frameborder='0' width='100%'></iframe>
</article>
</section>
<main id='main'>
<article class="content">
"'I had NOT!' cried the Mouse, sharply and very angrily. 'A knot!' said Alice, always ready to make herself useful, and looking anxiously about her. 'Oh, do let me help to undo it!' 'I shall do nothing of the sort,' said the Mouse, getting up and walking
away. 'You insult me by talking such nonsense!' 'I didn't mean it!' pleaded poor Alice. 'But you're so easily offended, you know!' The Mouse only growled in reply. 'Please come back and finish your story!'
</article>
<article class="content">
Alice called after it; and the others all joined in chorus, 'Yes, please do!' but the Mouse only shook its head impatiently, and walked a little quicker. 'What a pity it wouldn't stay!' sighed the Lory, as soon as it was quite out of sight; and an old
Crab took the opportunity of saying to her daughter 'Ah, my dear! Let this be a lesson to you never to lose YOUR temper!' 'Hold your tongue, Ma!' said the young Crab, a little snappishly. 'You're enough to try the patience of an oyster!' 'I wish
I had our Dinah here, I know I do!' said Alice aloud, addressing nobody in particular.
</article>
<article class="content">
'She'd soon fetch it back!' 'And who is Dinah, if I might venture to ask the question?' said the Lory. Alice replied eagerly, for she was always ready to talk about her pet: 'Dinah's our cat. And she's such a capital one for catching mice you can't think!
And oh, I wish you could see her after the birds! Why, she'll eat a little bird as soon as look at it!' This speech caused a remarkable sensation among the party. Some of the birds hurried off at once: one old Magpie began wrapping itself up very
carefully, remarking, 'I really must be getting home; the night-air doesn't suit my throat!' and a Canary called out in a trembling voice to its children, 'Come away, my dears! It's high time you were all in bed!'"
</article>
<article class="content">
"Death!" I shouted. "Death is coming! Death!" and leaving him to digest that if he could, I hurried on after the artillery-man. At the corner I looked back. The soldier had left him, and he was still standing by his box, with the pots of orchids on the
lid of it, and staring vaguely over the trees. No one in Weybridge could tell us where the headquarters were established; the whole place was in such confusion as I had never seen in any town before. Carts, carriages everywhere, the most astonishing
miscellany of conveyances and horseflesh. The respectable inhabitants of the place, men in golf and boating costumes, wives prettily dressed, were packing, river-side loafers energetically helping, children excited, and, for the most part, highly
delighted at this astonishing variation of their Sunday experiences. In the midst of it all the worthy vicar was very pluckily holding an early celebration, and his bell was jangling out above the excitement.
</article>
<article class="content">
I and the artilleryman, seated on the step of the drinking fountain, made a very passable meal upon what we had brought with us. Patrols of soldiers--here no longer hussars, but grenadiers in white--were warning people to move now or to take refuge in
their cellars as soon as the firing began. We saw as we crossed the railway bridge that a growing crowd of people had assembled in and about the railway station, and the swarming platform was piled with boxes and packages. The ordinary traffic had
been stopped, I believe, in order to allow of the passage of troops and guns to Chertsey, and I have heard since that a savage struggle occurred for places in the special trains that were put on at a later hour.
</article>
<article class="content">
We remained at Weybridge until midday, and at that hour we found ourselves at the place near Shepperton Lock where the Wey and Thames join. Part of the time we spent helping two old women to pack a little cart. The Wey has a treble mouth, and at this
point boats are to be hired, and there was a ferry across the river. On the Shepperton side was an inn with a lawn, and beyond that the tower of Shepperton Church--it has been replaced by a spire--rose above the trees. Here we found an excited and
noisy crowd of fugitives. As yet the flight had not grown to a panic, but there were already far more people than all the boats going to and fro could enable to cross. People came panting along under heavy burdens; one husband
</article>
</main>
<section class="sec">
<article class="content">
<img src='https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png'>
</article>
</section>
<footer>
<nav id="end">To Top
</nav>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
//Delagate: click event to all anchors
$("a").on('click', function(event) {
//Condition: If this anchor has "href=#" then...
if (this.hash !== "") {
//Inhibit: Default behavior of anchor
event.preventDefault();
//Store anchor's "#"
var hash = this.hash;
/*
||Target the root and parent of page content.
||.animate() scrolling from clicked anchor to
||location designated by the anchor's hash.
*/
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
//return anchor behavior to anchor
window.location.hash = hash;
});
}
});
});
</script>
</body>
</html>
My HTML Code is :
<!DOCTYPE html>
<html>
<head>
<title>Furry Friends Campaign</title>
<link rel="stylesheet" type="text/css" href="styles/my_style.css">
</head>
<body>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#clickMe").click(function()
{
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
</body>
</html>
The accompanying CSS looks like:
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
The slideToggle works perfectly, but for some reason, the image doesn't fade in. I've tried setting the duration to longer periods, but that yields the same results. Can someone point out what's wrong with this code? I'm using the latest version of Chrome.
UPDATE: I tried running the example code of the book I was using, which uses jquery-1.6.2.min.js and using that version of jQuery, the code works perfectly. Is this some error on jQuery's part? Or is the new way that things will be done now?
Since jQuery 1.8, fadeIn no longer initially hides the image, so trying to fade in an image which is visible or doesn't have display set to none won't lead to anything.
To fade in, you should hide it first. Initially it's not hidden, since children don't inherit display CSS property, and you have set it to none only on #picframe, the parent of img. Just add $("img").hide(); on ready. This will make it work.
Since it looks like you need to fade it in / out with each click, you could do the following instead of $("img").fadeIn(1000):
if($("img").is(":hidden")) $("img").fadeIn(1000);
else $("img").fadeOut(1000);
Demo below.
#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}
#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$("img").hide();
$("#clickMe").click(function() {
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
Somehow, img didn't inherit the display:none in #picframe div. Here's the fix: https://jsfiddle.net/69rLha7e/1/
There is a "timing" consideration while playing with multiple animations a time.
In this CodePen, I used diferent timing for fadeIn, fadeOut and toggleSlide.
And you have to check the display state in order to decide to fade in or out.
$(document).ready(function(){
$("#clickMe").click(function(){
console.log( $("img").css("display") ) ;
if( $("img").css("display")=="inline" ){
$("img").fadeOut(400);
}else{
$("img").fadeIn(800);
}
$("#picframe").slideToggle(400);
});
});
I am trying to build a simple web page for my website using HTML, CSS, JavaScript and JQuery. What I want is to display a slideshow of a few of my images at the top of the page. I just want the pictures to fade out and fade in after one another forever until the user closes the browser. I want each picture to be displayed for a certain amount of time, after which it will fade out and another picture would fade in.
I referred to this as well as this post on SO but couldn't find a solution. I got some idea from this page and tried to develop some code.
The overall layout of the website is as follows:
For this, my index.html page looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" href="css/style.css" />
<script language="javascript" src="js/jquery-1.10.2.min.js"></script>
<script language="javascript" src="js/common.js"></script>
<script language="javascript" src="js/banner_rotator.js"></script>
</head>
<body onload="loadBody();">
<div id="wrapper">
<img id="headerlogo" />
<div id="nav">
Home
About
Weddings
Portraiture
Landscapes
Products
Miscellaneous
Services
Contact
</div>
<div id="container">
<div id="content">
<!-- Main content starts here -->
<p>
Welcome to the world of The Siblings' photography.
</p>
imgpos = <span id="imgposspan"></span>
<!-- Main content ends here -->
</div>
</div>
</div>
</body>
</html>
The CSS is like this:
body {
background-color: transparent; color: #d0d0d0;
font: normal normal 11px verdana; margin: 0 auto;
}
#wrapper {
background-color: transparent; width: 960px; margin: 0 auto;
}
#headerlogo {
border-radius: 0px 0px 5px 5px; display: block;
width: 960px; height: 350px;
background-color: #d0d0d0;
}
#container {
width: 100%; margin-top: -35px;
}
#nav {
background-color: transparent;
color: #888888; border-radius: 5px; padding: 10px;
width: 100%; position: relative; top: -40px;
}
#nav>a {
border-radius: 5px; display: inline-block; padding: 5px 19px;
font-weight: bold; border: 1px solid transparent;
color: #888888; background: none none transparent no-repeat;
}
#nav>a:link {
text-decoration: none; border-color: transparent; background-image: none;
}
#nav>a:visited {
text-decoration: none; border-color: transparent; background-image: none;
}
#nav>a:hover{
text-decoration: none; border-color: #ffa500; background-image: url("/img/1x30_ffa500.gif");
background-repeat: repeat-x; box-shadow: 0px 0px 5px #ffd700;
}
#nav>a:active {
text-decoration: underline; border-color: transparent;
background-image: none;
}
#content {
background-color: #f0f0f0; color: #202020;
padding: 5px; border-radius: 5px;
}
The common.js file is like this:
$(document).ready(function (){
var images = new Array();
images[0] = new Image();
images[0].src = "img/coverpics/sea_link.jpg";
images[1] = new Image();
images[1].src = "img/coverpics/marine_drive.jpg";
images[2] = new Image();
images[2].src = "img/coverpics/backbay.jpg"
banner_rotator("headerlogo", images, 0);
});
And, the banner_rotator.js file is like this:
function banner_rotator(imgid, imgarray, imgpos) {
setInterval(function() {
if (imgpos >= imgarray.length || imgpos == undefined)
imgpos = 0;
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000, "linear");
$("#"+imgid).delay(6500);
$("#"+imgid).fadeOut(500);
// $("#imgposspan").html(imgpos);
imgpos++;
}, 8000);
}
Now, my problem description is as follows:
For the first few seconds the top portion is blank. The image is not showed, even though I am developing and having all the files on my local machine itself.
This first image directly pops up on the screen, instead of fading in.
After this image fades out, the image block vanishes, as if it is set to display: none; for a second. The entire page that follows the image shifts up. Then, the next image fades in and so forth everything runs normal.
Hence, in short, I have problems with the starting of this slideshow. Can anybody please help?
Also please tell me where can I put my code so everybody here can access and see for themselves how it runs?
JSFIDDLE
<img id="headerlogo" />
Don't do that (an image tag with no src attribute)
Put a div that will hold the space (set position:relative with width & height in css)
Then the problem is that you are changing your src attribute in your time loop, this ain't smooth
In your CSS, suppose you name your slider wrapper headerlogo_wrapper
div.headerlogo_wrapper > img {position:absolute;display:none;left:0;top:0}
Then you append your images to the space holder you have created (they will not show obviously)
Then you fadeIn your first image then you launch your setInterval :
//after having appended the images to the slider wrapper :
var $img = $("div.headerlogo_wrapper > img");
$img.eq(0).fadeIn(1000, "linear");
var ivisible = 0;
setInterval( function() {
$img.eq(ivisible).fadeOut(500);
++ivisible;
if (ivisible>$img.length-1) ivisible = 0;
$img.eq(ivisible).stop().fadeIn(1000, "linear");
}, 8000);
(If you want an image to be shown during load, some simple changes shall do; also if the first interval start immediately you obviously don't need to fadeIn "manually" the first image)
Try this: http://jsfiddle.net/3XV5M/
Your problem is the first time you run the timer function it won't run straight away. It will be run after 8000ms. The way this fiddle works is it will execute the function immediately and the run itself again after 8 seconds. Note I'm using setTimeout instead of setInterval.
function banner_rotator(imgid, imgarray, imgpos) {
if (imgpos >= imgarray.length || imgpos == undefined) imgpos = 0;
$("#"+imgid).attr({ "src" : imgarray[imgpos].src })
.fadeIn(1000, "linear")
.delay(6500)
.fadeOut(500);
imgpos++;
setTimeout(function() {banner_rotator(imgid, imgarray, imgpos) }, 8000);
}
The other problem is you need to hide the images first, so they can fade in. They wont fade in if they are already visible.
#headerlogo {
border-radius: 0px 0px 5px 5px;
width: 960px; height: 350px;
background-color: #d0d0d0;
display: none; /* Add this */
}
Then to prevent the other elements jumping up when you fade the images out, wrap the image element inside a div and set it's height. I used a div with a class of banner and added this style:
.banner {
height: 350px;
}
Hope that helps.
The problem is that you are fading out at the end of your interval. So replace this:
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000, "linear");
$("#"+imgid).delay(6500);
$("#"+imgid).fadeOut(500);
with this:
$("#"+imgid).fadeOut(500)
$("#"+imgid).queue(function(){
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000);
$("#imgposspan").html(imgpos);
imgpos++;
$(this).dequeue();
});
JSFIDDLE demo