I run a free resource site providing tileable/seamless patterns and I'm trying to add a button (with a script) in my posts which visitors can click to change the background image of the page so that they can preview the pattern in action. So for instance on this post (http://tileablepatterns.com/denim-pattern/) I'd want the user to be able to click on a button/link which would change the background image from the grey background to the denim pattern.
How do I go about doing this? Also, preferably I'd want it to be a simple script that I can just insert into the post instead of having to edit theme files.
Thanks a lot for any help!
Give your button an ID, for example: id="button" and then the following should work:
$('#button').click(function(){ $('body').css('background', 'url(http://tileablepatterns.com/wp-content/uploads/2014/09/Denim.jpg) repeat 0 0'); });
So basically I tried this <button onclick="document.body.style.background = 'url(http://tileablepatterns.com/wp-content/uploads/2014/09/Denim.jpg) no-repeat center center'">change bg</button>
And it adds two white lines to the existing background, one close to the top and one close to the bottom but it's not changing the entire background. I think there's a wrapper over the background or something but I don't know how to change the code so that it changes the entire page's background including the wrapper?
If I were to do this using jQuery, I'd take a modular approach and one that's easy to template in HTML and still works when Javascript fails.
Start with some basic markup (I'm using Baconmockup as a sample image):
<div id="page" class="container">
<!-- Note that we're defining both href as well as two html5 attributes called data-src and data-background-change (data-background-change is what indicates that this particular link has some special functionality and data-src is the the source for the script below) -->
<a href="https://s3.amazonaws.com/baconmockup/img/baconmockup-470-300.jpg" data-src="https://s3.amazonaws.com/baconmockup/img/baconmockup-470-300.jpg" data-background-change>Click me</a>
</div>
And a bit of CSS:
// The container is your page, and the background we'll change in this example.
div.container {
background: red;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
And finally in main.js:
$(function () {
$.fn.changeBackgroundOnClick = function () {
var target = this[0];
var image = target.getAttribute('data-src');
$(target).on('click', function(e) {
// If JS is enabled, the click will prevent the browser from navigating to the image.
e.preventDefault();
$('#page').css({
'background-image' : 'url(' + image + ')',
'background-size' : 'cover',
'background-repeat' : 'no-repeat'
});
});
return this;
}
// We can now iterate over every element with data-background-change to give it the functionality you need. No code needs to be repeated. :)
$('a[data-background-change]').each(function () {
$(this).changeBackgroundOnClick();
});
});
Good luck.
Check out this fiddle: http://jsfiddle.net/Nyyby/31/
Related
I'm applying a repeated background image from a canvas to a div via javascript like this:
var img_canvas = document.createElement('canvas');
img_canvas.width = 16;
img_canvas.height = 16;
img_canvas.getContext('2d').drawImage(canvas, 0, 0, 16, 16);
var img = img_canvas.toDataURL("image/png");
document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';
I have to update it quite frequently. The problem is it flickers upon change, it doesn't appear to happen in Chrome but it's really bad in Firefox and Safari. Is it possible to stop this? I didn't think it would happen since it's a dataurl and therefore doesn't need to be downloaded.
Solution:
// create a new Image object
var img_tag = new Image();
// when preload is complete, apply the image to the div
img_tag.onload = function() {
document.querySelector('#div').style.backgroundImage = 'url(' + img + ')';
}
// setting 'src' actually starts the preload
img_tag.src = img;
Try to preload the image resource to the device storage by including the image in DOM like in the following HTML-Code. Maybe the error comes up because the image resource need to be loaded which takes some time (flickering).
<img src="imageToPreload.png" style="display:none;" alt="" />
You may prefer to use sprites-images. By using sprites your application will need less HTTP-Requests to load all ressources into your page. Also add the following CSS styles if you are using css animations. It will prevent background flickering on mobile devices:
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
Preload your image like this, no need to include a <img> with display: none
<link rel="preload" href="/images/bg-min.png" as="image">
Try adding this css to your background element:
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
It should help with flickering..
You can also "force" hardware acceleration by adding this to your background element:
-webkit-transform: translate3d(0, 0, 0);
Another option is to use image instead of DIV and change only the image url.
I struggled with this for a bit, tried preloading, appending the image to the document, etc.
In the end, I resaved the JPEG without the "Progressive" option.
That fixed the rolling flicker when the img src was swapped.
In my case changing height: 1080px; (background height) to height: fit-content;
I think that preloading all the images is essential in any case. What I found is that the way the browsers behave while changing the background image dynamically is different from one another. In Firefox for example it flickers when the change is frequent however in Chrome and Safari it doesn't.
The best solution I came up with so far is drawing the image inside a child canvas that fills the space of the whole parent div.
In all cases, the images you are using must be optimized as it affects the rendering performance.
My javascript code that works now, looks like this
const pic = new Image();
const pic2 = new Image();
pic.src="../images/settings_referrals_anim.gif";
pic2.src="../images/settings_referrals_still.png";
I don't actually reference that code in the query, for example, i use
document.querySelector(".button_Settings_referrals").addEventListener("mouseover", function() {
myDiv.style.backgroundImage = "url('../images/settings_referrals_anim.gif')";
But it seems to work. If I replace the long URL with const pic for example it doesn't work, and if I include the image object declaration and location at first time in the assignment, then the flickering stops.
This does not address all of the specifics noted by the OP, but might be useful for others. Tested in Chrome 97, Firefox 96, Android 11, iOS 15.
I have a div that includes these CSS parameters...
#div_image {
background-image: url( [Path to low-res image] );
background-size: cover;
}
I have a corresponding class that looks like this...
.div_image_highres {
background-image: none !important;
}
The corresponding class has a pseudo-element defined as follows:
.div_image_highres::before {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
content: " ";
background-image: url( [Path to highres image] );
background-repeat: no-repeat;
background-position: 50% 0;
background-size: cover;
opacity: 1;
display: block;
}
I have an img element that also points to the high-res image...
<img id="img_highres_preload" src=" [Path to high-res image ] ">
The img element has a corresponding style which allows the image to be displayed (ensuring that image file loads) but not seen...
#img_highres_preload {
width: 1px;
height: 1px;
}
Two notes: (1) I realize a lot of people use other methods of pre-loading (e.g., programmatically), but I have a personal preference for this method. (2) See the addendum about the reliability of the load event.
Last but not least, I have some Javascript (jQuery) that adds the "high-res" class to "div_image" once the high-res file is loaded...
$(document).ready(function() {
$("#img_highres_preload").off().on("load", function() {
$("#div_image").addClass("div_image_highres");
});
});
This could easily be vanilla JS, but since I use jQuery throughout my code, I like having a consistency.
Here's a summary of what's happening...
Presumably, the low-res image is loaded first and becomes the background image for the div. Even if that does not occur, everything will work as intended (i.e., the high-res image will be displayed).
When the high-res image loads into the img element (i.e., Javascript confirms that the high-res file is loaded), the "div_image_highres" class is applied to "div_image".
As result, the div switches to the high-res image without flashing. In my experience, if anything, it shifts a little to the left; but that often doesn't occur and, if it does, it's not inelegant.
And here's the primary reason I use this approach when required: In my application, there are multiple panels the user can navigate, which results in one panel sliding out of view and the new one into view. If I don't use a pseudo-element (as described above) for displaying a high-res image, the image flickers when its div is hidden and re-displayed. With the above-described technique, I can slide the div in and out of view without any flickering.
Regarding the Load Event
You can't depend on the load event firing. For instance, it typically does not fire when the browser has cached an image. So to make a long post even longer, here's the enhancement I have in my code to accommodate that reality...
I modify the document.ready event (shown above) to look like this:
$(document).ready(function() {
positionOnPage(true);
$("#img_highres_preload").off().on("load", function() {
checkImage();
});
});
checkImage = function() {
var image = $("#img_highres_preload")[0];
if (!image.complete || (typeof image.naturalWidth != "undefined" && image.naturalWidth == 0)) {
console.log("Waiting for high-res image.");
}
else if (!$("#div_home").hasClass("div_home_highres")) {
$("#div_home").addClass("div_home_highres");
$("#img_highres_preload").remove();
}
}
The checkImage function examines the image element to see whether an image has in fact been loaded. In this code example, it is a little redundant — that is, the img element has confirmed the load, so there's usually no need to check it (unless there is some reason to believe the file is being misloaded).
I might do it as shown because I also call checkImage from other places in my code, so if I have more of a programmatic response (unlike the simple version shown), I want all of that code in the same place and written just once. The checkImage function might be called when triggered by a timer or when the section displaying the intended image is about to be displayed. Perhaps something like this...
if (sectionName == "[whatever]" && $("#img_highres_preload").length === 1) {
checkImage();
}
In this example, I look for the presence of the preload img element because I know that my previous function removes the element after it has fulfilled its purpose.
This post has a stripped-down version to illustrate the concept. As written above, it only accommodates a single known img element, so the code could be extended to call checkImage with some parameters (e.g., the name of an image or the element itself) and checkImage could look for the existence of the preload element, so that check occurs in one place. It can be fairly fancy, so I went with the simplest example for this post.
In many cases, this stripped-down version is all I need because typically I only use a high-res photo for a window background image. I either start with the display of a low-res image and switch it out as soon as the high-res file is loaded, or I have some animation that gets triggered after I confirm the presence of the high-res image.
A good case for a more generalized version is when I need a series of images loaded at the outset and don't want to start until all of them are ready. In those cases, the web page might begin with some welcome text that stays displayed until all images have been confirmed.
Hey Guys I know this has been an older question but if you are still flickering after all this you can simply put the final version behind you background div. That flicker is seeing behind the image you currently have so if its the final image it will be smooth.
I want to place a "PLAY" div above each iframe. I want to do it automatically.
I manage to do that manually but I don't know how to do it with a script , or with css.
Here is my HTML markup :
<ul data-role="listview" id="resultat"></ul>
And my Javascript code :
$('#resultat').append('<li class="liste" ><iframe id="ytplayer" type="text/html" width="140" height="100" src="http://www.youtube.com/embed/RD98kNOBrNs?hd=1&rel=0&autohide=1&showinfo=0&wmode=opaque" frameborder="0"/></li>').listview("refresh");
I'm using z-index and position attributes to place my div manually above the iframe, but I don't think it's a good idea to do it automatically.
Thanks
In addition to Matyas his answer, I have altered his code a bit such that it is now fully implementable.
First, take a look at the demo before I will explain all the details:
SEE DEMO CODE HERE
As you can see, I 'soft coded' all the widths and the heights such that the overlayDiv is placed exactly in the middle of the iFrame.
You can change the width and the height of the overlayDiv to whatever you want and the script will automatically adjust the position of the start button.
What is very important is that you must have the following order in your HTML for this to work:
<div id="vidFrame" class="play">
<iframe id="video" class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/-PZLM-CmuJ0?wmode=opaque&hd=1&rel=0&autohide=1&showinfo=0&enablejsapi=1" frameborder="0"></iframe>
</div>
<div class="overlayDiv">
<img src="https://www.ameliaconcours.org/UploadedContent/Lamborghini%20Logo_Crest_4C_S.png" alt="facebook" width="90px" />
</div>
Where the width and height of vidFrame doesn't have to be established beforehand because it will become the height of the iFrame.
Also, mind the following details:
wmode=opaque is the first argument we give to the video (must be the absolute first)
we enable the enablejsapi=1 such that we gain control over playing (and pausing) the video
The jQuery that I use is the following:
$.fn.loadOverlay = function() {
$('iframe').each(function(idx, iframe){
var imageHeight = $('.overlayDiv').height();
var imageWidth = $('.overlayDiv').width();
var marginTop = $('#video').height();
var marginTop = marginTop/2-imageHeight/2;
var marginLeft = $('#video').width();
var marginLeft = marginLeft/2-imageWidth/2;
$('.overlayDiv')
.clone()
.appendTo('body')
.css({
top: marginTop,
left: marginLeft,
}).show();
});
}
Note that, eventhough it is lengthy, it explicitly calculates the middle of the iFrame. Hence, shorter methods are possible but this one will make you understand exactly what is happening.
Now another thing: yt players always have the ugly red play button in the middle of their iFrame when loading a video.
There is a little hack to make this button disappear, namely:
function onPlayerReady(event){
//THIS IS THE TRICK THAT YOU MIGH WANT TO REMOVE
player.playVideo();
player.pauseVideo();
}
So essentially we play and then immediately pause the video to make the button disappear.
But mind you: this wil not work on mobile devices. A very big advantage of this is that the video will automatically start buffering which is an advantage for the user.
Furthermore, the jsFiddle is self-explanatory so just read it through and try to understand it.
I hope this answers your question. Good luck!
$('iframe').each(function(idx, iframe){ // for each iframe
var $iframe = $(iframe); // take its jquery reference
$('.overlayDiv') // grab the overlay template you wish to place over each
.clone() // clone it
.appendTo('body') // add it to the end of your page
.css({ // resize and position the overlay
top: $iframe.offset().top, // to fit just above the iframe
left: $iframe.offset().left,
height: $iframe.height(),
width: $iframe.width(),
}).show(); // show the hidden (by CSS) overlay
});
Initially your .overlayDiv should have the following styles:
.overlayDiv {
position: absolute; /* so when we position by js it will be above the iframe*/
display: none; /* the master tempalte should be hidden */
z-index: 4953; /* make sure the overlay appears above other elements */
}
I haven't tested it out, Just written it from scratch while my build was running. But this is the idea I'd go with. You might have to tinker with the positioning.
I am currently using display:none to hide all the divs on my website. Users click on like for example "info" or "contact" and the appropriate div will slide down via JQuery. To support users without Javascript, the links goes to "info.php" and "contact.php" if Javascript is no enabled.
This is quite a hassle to maintain because I have to update both the main page and the non-javascript versions (info.php, contact.php etc) when I make any changes.
What is a sensible back up to JQuery sliding divs for users without Javascript?
When I have understood you right, make a php-file with the static content. (The content on all sites) und include the content (info/contact) per include from another file depending on a GET Param like "page".
Hide the <div>s with jQuery so that users without JavaScript can still see all the <div>s in one long page. Users with JavaScript, on the other hand, can slide the <div>s as usual.
jQuery IS JavaScript - is cannot be a backup plan.
one does not simply use the terms JavaScript and jQuery interchangeably
jQuery is a JavaScript library. By disabling JavaScript, the jQuery scripts will not be able to hide the <div>s. The key is to keep it functional when JavaScript is not available. As long as you do not perform critical manipulation to the page that would render it non-functional without JavaScript, you can cater for those non-JavaScript users. In this case, putting the modification work over to jQuery (or JavaScript) is a way to preserve functionality.
At first add a class to_hide to all divs which should be hidden when javascript is activated.
The simplest way is to hide the divs like this on page load:
$(document).ready(function() {
$('.to_hide').hide();
});
Note that if you do this, the layout will blink when loaded (the full content will be shown at first and then the dynamic divs will be hidden).
To avoid blinking you can add css rule for to_hide class dynamically. Use the following function in the <head> to do that:
function dyn_css_rule(sSelector, sCssText) {
try {
var aSS = document.styleSheets;
var i;
for (i=aSS.length-1; i>=0; i--) {
var oCss = document.styleSheets[i];
var sMedia = (typeof(oCss.media) == "string")?
oCss.media:
oCss.media.mediaText;
if (!sMedia
|| sMedia.indexOf("screen") != -1
|| sMedia.indexOf("all") != -1
) {
break;
}
}
if (oCss.insertRule) {
oCss.insertRule(sSelector + " {" + sCssText + "}", oCss.cssRules.length);
} else if (oCss.addRule) {
oCss.addRule(sSelector, sCssText);
}
} catch(err) {
var tag = document.createElement('style');
tag.type = 'text/css';
try {
tag.innerHTML = sSelector + " {" + sCssText + "}";
} catch(err) {
tag.innerText = sSelector + " {" + sCssText + "}";
}
document.getElementsByTagName('head')[0].appendChild(tag);
}
return sSelector + "{" + sCssText + "}";
};
dyn_css_rule('.to_hide', 'display: none');
A Pure CSS Solution
This may or may not work depending on the situation, but you can actually mimic a drop-down menu's behavior with css selectors in IE8 and up. Here's an example. Click on the menu, and as long as you hover around the content the content will appear, no javascript required.
Functionality
By default, all the content is hidden. However, thanks to the :active pseudoclass, you can change the content to display when the parent is clicked. This is pretty inconvenient though - the user has to hold down the mouse to see anything. However, we can cheat a bit - by adding a :hover pseudoclass that displays the content, if the user clicks and hovers the content will stick around.
So far, we have this css:
.container.content {
display: none;
}
.container:active .content {
display: block;
}
.content:hover {
display: block;
}
This is a little flaky though - you have to move your mouse down over the content to have it persist, and will likely confuse. We can cheat a bit though by making the content larger than it appears. A simple way to do this would to be just to padding (that's what I've done in the example I added), but this can cause some odd reflow issues. A better way I think is to add deliberate spacing divs that add to the size of the content without changing the flow.
If we add this
<div style="position:absolute; top:-50px; height: 50px; width: 100%;"></div>
to the start of the content, there's an invisible div hovering over the menu, which will extend the area on which hover works. A similar thing can be done to the bottom, leaving us with a solution that has a larger hover area, and doesn't trigger reflows beyond the main content.
Remaining Problems
Anyway, this isn't perfect since it certainly isn't as flexible as javascript. There's no sliding, and you can't reliably make the content show up if the user mouses out.
As other people suggested, you can still improve this with javascript after the fact should the user have it enabled though - this can still work as a decent backup to noscript users.
I ended up using a solution that combines Antony's answer and this answer: https://stackoverflow.com/a/8928909/1342461
<html class="no-js">
<body>
<div id="foo"></div>
</body>
</html>
#foo
{
display: none;
}
html.no-js #foo
{
display: block;
}
$(document).ready(
function()
{
$('html').removeClass('no-js');
}
);
All the divs will be seen by people without javascript. Then, I can set my navigation links to a href="#info" for example, to get it to scroll down to the correct div for non-javascript users while doing "slide.down()" etc for javascript users.
Have your info.php main text in an include file. Lets say info.inc.php
When non-js user clicks the link, they go to info.php into which the include file is, well, included.
But when a js user clicks the link, you load the info.inc.php onto your div and only THEN show it with jquery.
Say
$('a.info').click(function(e){
e.preventDefault();
$('#infoDiv').load('info.inc.php')
.show();
return false;
});
When you need to update content, just update the include file.
I do have an URL which opens a webpage which is very slow to load and I have no control over it.
I do want to display a loading dialog when someone clicks this URL or to block page with an overlay div when this happens.
Note: this is not the same question as the ajax related ones, this for normal URL clicks form the user, not all of them only specific ones.
slow load...
I suppose that what I am looking for is what to put on the onClick.
You can do this :
$(function(){
$('a').click(function(){
$('<div class=loadingDiv>loading...</div>').prependTo(document.body);
});
});
Demonstration (change the link to a very slow page for best effect)
But it depends on the page : if the page sends immediately some content but not the whole content, you won't have the time to see your div.
If you also need an animation, it becomes a complicated matter as browsers behave very differently. Some stop all GIF animations when a new page starts loading. Basically it comes down to something like this if you have jQuery and download the spin.js library.
See working solution here:
http://jsfiddle.net/7aJyP/
<style>
#loading {
display:none;
position:absolute;
left:0;
top:0;
z-index:1000;
width:100%;
height:100%;
min-height:100%;
background:#000;
opacity:0.8;
text-align:center;
color:#fff;
}
#loading_anim {
position:absolute;
left:50%;
top:50%;
z-index:1010;
}
</style>
<div id="loading"><div id="loading_anim"></div></div>
link
<script>
$(function () {
$(".withanimation").click(function(e) {
e.preventDefault();
$("#loading").show();
var url=$(this).attr("href");
setTimeout(function() {
setTimeout(function() {showSpinner();},30);
window.location=url;
},0);
});
});
function showSpinner() {
var opts = {
lines: 15, // The number of lines to draw
length: 3, // The length of each line
width: 4, // The line thickness
radius: 30, // The radius of the inner circle
rotate: 0, // The rotation offset
color: '#fff', // #rgb or #rrggbb
speed: 2, // Rounds per second
trail: 70, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: 'auto', // Top position relative to parent in px
left: 'auto' // Left position relative to parent in px
};
$('#loading_anim').each(function() {
spinner = new Spinner(opts).spin(this);
});
}
</script>
If you use an animated (GIF) the animation may freeze on some browsers. I used spin.js library ( http://fgnass.github.com/spin.js/ ). While GIFs get frozen the javascript animation seems to be working.
Please test with ALL browsers!
Although ajax would be more elegant, it's possible. You have to intercept the navigation by preventing the default event, then force an update to the UI, then change the location to the destination url. Something like this:
$('#mylink').click(function(e) {
e.preventDefault();
var url = this.href;
// Update the UI here
setTimeout(function() {
// This is a trick to force a repaint
window.location.href = url;
},0);
});
This is an old topic, but if you want a simple solution that doesn't depend on JQuery add the following to onClick in your link:
slow load...
Then somewhere on your page, have a hidden DIV that includes what you want for the loading dialog.
<div id="page-loader">
<h3>Loading page...</h3>
</div>
and hide the DIV with CSS as follows:
#page-loader {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 25px;
background-color: rgba(255, 255, 255, 0.7);
}
Here's a JSfiddle to a working example: http://jsfiddle.net/meb69vqd/
I can't take full credit for this example. There are additional tips about this technique here: https://css-tricks.com/css-page-loader/
Presumably, you'll want the loading dialog to appear immediately, then to disappear and be replaced by the new page when the new page has rendered?
Three ideas come to mind.
If you have control of the source page but not the target - Use a click event handler to replace the tags' normal behavior with something like this:
Display the loading animation
Fire an AJAX request to the URL defined by the tag's href attribute (alternately, create a hidden with the URL as its source)
When the request has completed, replace the document's contents with the response.
This can get really hairy, though, since you won't lose javascript and css defined in the original page. It also won't change the URL displayed in the user's browser.
If you have control of the target and can make the target cacheable (even for a few seconds): You could load the page in the background via AJAX and then redirect to it. The first load will be slow, then the redirect will load the page from cache.
And yet another alternative: If you have control of the target page, you can define an optional parameter such that if the parameter is present, the server returns a page consisting of only the loading animation and a bit of javascript that loads the actual page.
initially store a spinner.gif some where in your form and keep it hidden
and also put src=""
thus there will be no src for image
but later on while making the ajax call you can set the src for the spinner image thus you page will seem to be loading
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'url to be called',
type:'post',
beforeSend:function()
{
alert("this is the place where you place things to happen till your page is being transfered to the given URL so i am setting the src for the spinner image here");
$("#spinner image ID").attr("src","../images/spinner.gif");
},
success:function(e){
alert("do whatever you want with response here");
}
});
});
You can create a hidden iframe and listen for the load event. You will also need to do a manual check after about 1 sec, in case the destination has prevented x-frame content.
DEMO: http://jsbin.com/ijofih/1
$('a').click(function(e) {
$(this).text('Loading...'); // do your UI thing here
e.preventDefault();
var destination = this.href;
setTimeout(function() {
window.location = destination;
},1000);
$('<iframe>').hide().appendTo('body').load(function() {
window.location = destination;
}).attr('src', destination);
});
an improvement over #bfavaretto 's solution that worked for me
$('#mylink').click(function(e) {
e.preventDefault();
var url = this.href;
// Update the UI here
requestAnimationFrame(function() {
setTimeout(function() {
window.location.href = url;
});
});
});
the browser would inconsistently display my spinner. I tried hacking around with increasing the setTimeout's delay. The proper solution is to ask the browser when it is ready to show the spinner, then navigate away.
You might want to look into Modal boxes. You can activate a model box when the ajax request is send and on success maybe close it.
https://www.google.com/search?sugexp=chrome,mod=10&sourceid=chrome&ie=UTF-8&q=modal+box
I'm trying to figure out how to create a popup box with user profile details on mouseover like you see on google plus. When hovering over a thumbnail a popup appears with the option to add that person into your circle.
It seems kinda simple to do with jQuery but I've been unable to find a simple solution. Most of the plugins I've come across are too complicated and require a lot of tweaking. Any help on how to do this would be greatly appreciated!
Hover Effect Screenshot
You'll want to try something like this. It doesn't handle all the cases you'll need (you need the hover to stay active when user enters the popup); but you can work some of those out I hope.
Here's the basic jQuery code:
jQuery(function($) {
function getMyContent($img) {
// do your fancy ajax calls or append your control links and such here
return $('<p />').append($img.clone()).append('Here is my fancy hoverbox');
}
$('#content img').mouseenter(function(e) {
var $this = $(this), off = $this.offset();
var pos = {
// or you could position it relative to the mouse
top: (e.clientY + 2) + 'px',
left: (e.clientX + 2) + 'px'
};
$('#hoverbox').css(pos)
.append(getMyContent($this))
.fadeTo('slow', .95);
}).mouseleave(function(e) {
$('#hoverbox').fadeOut('slow', function() { $(this).html(''); });
});
});
UPDATE: Here is one that handles the hover events on the popup for you (yeah, I'm still messing around with it; why?)
The simplest solution would be to add a hidden div to the element that wraps around your profile photo.
<div class="profile-popup" style="display: none;">
<!-- Popup info goes here -->
</div>
Go ahead and style the div with CSS however you want it to appear, say with absolute positioning at the bottom right corner for the "pop out" effect. Then register a mouseOver event in jQuery that shows the div:
$().ready( function() {
$('.profile-pic-wrapper').mouseenter( function() {
$('.profile-popup', this).show( //pass in some animation options here );
});
$('.profile-pic-wrapper').mouseleave( function() {
$('.profile-popup', this).hide( //pass in some animation options here );
});
});
This is just a basic idea (and that code may need to be tweaked a bit). You'll have to add some additional logic to keep the popup open when the user mouses into it, but this should get you started.
The more elegant solution would be to pass JSON data to your jQuery script and have it generate the popup div dynamically on hover, but that is a bit more advanced.