load file on hover using jQuery - javascript

I want to load an external file (using jQuery) when the user hovers a div. I tried loading it like a css file on hover but no luck. (Also, I can load a css file on hover, right? That code I tried for that is below.)
$(document).ready(function () {
$("#f1_container2").hover(function () {
$('head').append('<link rel="stylesheet" href="theme/supersized.shutter.css" type="text/css" media="screen" />');
});
});

You can load content using $(".target").load("file.html"), where file.html is an HTML fragment containing some markup.
Since CSS is passive (it doesn't do anything until someone uses it), it can sit in the head in the first place. That way, when you hover over a div, you can do $(".target").addClass("newClass") to apply some groovy styling.
hover() can also take a SECOND function, which is invoked when the mouse leaves the target, so you can undo whatever you did on the mouseover.

The document has already been loaded and rendered when you append the code for the stylesheet. The browser has already retrieved the needed resources and won't retrieve a file because you appended some code.
I would recommend, as mentioned, pre-loading your images or using another technique to retrieve the file on hover.
I believe something like this may work.
$(document).ready(function () {
$("#f1_container2").hover(function () {
// The easy way
//$('head').append('<img src="images/sprite.gif">');
// The cool way
var $img = $('<img>', {
src: 'images/sprite.gif',
load: function() {
$(this).fadeIn('slow');
},
css: {
display: 'none'
}
}).appendTo('body'); // append to where needed
});
});

Related

Need "document.write" to only write inside a specific element, not overwrite the whole page [duplicate]

I'm very new with javascript.
I'm trying to create a tag using document.write (with Wordpress) to add a style that hides images before they are preloaded. I've had to resort to writing a Javascript style to hide the images before they are loaded via CSS. I don't want to actually write it into the CSS file incase the user has Javascript disabled and then the images would never show.
I'm trying to get this code to work:
jQuery(function($) {
document.write('<style type="text/css"> .preload img { display: none; } </style>');
$('#body-wrap').preloadThis();
});
But, it is just overwriting the whole page and making it go blank. How can I stop this? I want to add the tag to the without removing the page. Tried using 'return', no luck.
Sorry, I'm a novice. Thanks in advance.
Using document.write() after the page has finished loading implicitly calls document.open(), which creates a new page. You should generally avoid document.write() and stick to proper DOM creation techniques, or use jQuery's shorthand creation methods:
jQuery(function($) {
$('<style type="text/css"> .preload img { display: none; } </style>')
.appendTo("head");
$('#body-wrap').preloadThis();
});
I'm assuming you can't edit the HTML or CSS files that are loaded by the page to include this rule? If that's the case, and you want these styles applied before the page finishes loading, take `document.write()` out of the jQuery ready handler:
// write() before the document finishes loading
document.write('<style type="text/css"> .preload img { display: none; } </style>');
jQuery(function($) {
$('#body-wrap').preloadThis();
});
This will write the <style> tag immediately after the currently executing <script> tag. Hopefully, this is in your <head> element as <style> is invalid anywhere else, although all browsers should parse it OK either way.
You don't need to add <style> tag, you can just hide them with jQuery:
jQuery(function($) {
$('.preload img').hide();
$('#body-wrap').preloadThis();
});
Don't know how your preloadThis() function works, but I guess it loads images and removes .preload class from img container. If it indeed works like that, this code will not help you - images will stay hidden.

Clean the CSS that was added while loading Ajax content

I am appending an HTML document into my current page using Ajax, and removing those added divs when the close button is pressed. The problem is that when I close, the divs are removed from the document but the CSS <link rel="stylesheet" href="style.css"> are not removed, and the number keep increasing as I load and unload Ajax content. How to completely remove the loaded document with the header content (css, js) of that page?
edit: i dont know why people dont want to answer but they just come to negative voting.
this is the code that i have used to add(append the html document)
$(function(){
$("a[rel='tab']").click(function(e){
pageurl = $(this).attr('href');
$.get(pageurl, function(html) {
$(html).hide().appendTo('body').fadeIn(500);
}, 'html');
//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
});
and this code to remove the divs
function close(){
$("#mainContent").fadeOut(500, function() { $(this).remove(); });
window.history.back();
} ;
I can't see the document that you are attempting to add/remove, but I'm guessing it looks something like this:
<link rel="stylesheet" href="style.css">
<div id="main-content">
<p>Blah blah blah</p>
</div>
So when you add that content, the whole thing is inserted. When you remove it, you are only removing the div#main-content. To remove everything, two ideas come to mind:
Preferably, wrap the document in another <div> and remove that instead
Alternatively, you could select <link> elements that are siblings of the 'div#main-content`, but that has the potential to be more unpredictable.
If the document you are adding doesn't look like that, then please explain in the OP what it does look like and where the <link> elements are coming from.
If you are doing something like a HTML preview in another page, look into creating an iframe instead. Use AJAX to create a temporary URL as the source. The advantage is that you avoid conflicts that occur when you effectively merge two DOMs.

How to make sure JQuery dynamically inject CSS properly and ready to use?

I know that I can do this to inject CSS like this:
$(document).ready(function() {
$("a").click(function() {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
});
But, this async. i.e. even I append the link, there is no guarantee that the css is available at that time. (because of the CSS download)
so, if there is another js runs at the same time and try to aasign a class, then
1) Will it still work? Will the css applied later on after the file is fully downloaded?
If not, is there something like a call back or some trick that I can use to know that the css is fully downloaded?
If you need it guaranteed to be loaded and the CSS is definitely on the same domain, you could request the contents via Ajax and then inject the properties directly.
I've had good luck doing this (in iOS at least) by creating a dummy <link> element in the <head> and calling text() on it with the contents of the CSS file (as a string).
For example, roughly:
$("a").click(function() {
$.get('style2.css', function (data) {
$('link').text(data);
// Stuff that must happen after CSS injection here
});
})
But honestly this is a rare use case.

Run JavaScript when title-tooltip is shown

I have a page with HTML anchor tags that have the title attribute set.
<a href="...." title="Some tooltip text" />
I want to detect when the tooltip is shown, and run some javascript. This is to log that the tooltip has been displayed. Using OnMouseOver isn't enough since it triggers too early.
Any ideas?
Mine would be to create your own tooltips that you could append extra 'tracking' to determine if they were displayed or not.
With that library, you could make your own effect that does customized things on the over/out of the tooltip.
Use JQuery. If you do sth only particular tags you must set your tags id and/or name attributes.
The code:
$(document).ready(function () {
$("#x").mouseenter(function () {
alert("yeah");
});
});
If you run javascript code for all <a> tags you use this like below.
$(document).ready(function () {
$("a").mouseenter(function () {
alert("yeah");
});
});
You add this between <head> tags of your page to use JQuery library
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

jQuery event that triggers after CSS is loaded?

I have a couple of links on my page (inside a <div id="theme-selector">) which allow you to change the CSS stylesheets:
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$('head link').remove();
$('head').append('<link type="text/css" href="'+path+'" rel="stylesheet" />');
return false;
});
Now, after I've changed the style on the page, I want to get the new background color, using the following code (which I put after the $('head').append call):
var bgcolor = $('body').css('background-color');
alert(bgcolor);
The problem is, I think, that it takes some time for the browser to download the new stylesheet and I sometimes get the old background color in my alert message. Is there some event I can bind that will only alert me after all the stylesheets are loaded on the page?
At the moment, all I can think of is using a setTimeout(function(){}, 5000); which isn't great, because what if it takes longer/shorter to load all the CSS on the page.
Let me know if I need to clarify anything and I can provide more code.
Rather than creating a new link element and appending it to the head, you could retrieve the contents of the stylesheet with an AJAX call, and insert it into an inline style block. That way, you can use jQuery's 'complete' callback to fire off your check.
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$.get(path, function(response){
//Check if the user theme element is in place - if not, create it.
if (!$('#userTheme').length) $('head').append('<style id="userTheme"></style>');
//populate the theme element with the new style (replace the old one if necessary)
$('#userTheme').text(response);
//Check whatever you want about the new style:
alert($('body').css('background-color'));
});
});
I haven't actually tested this code, so there may be some syntax-y errors, but the logic should be sound enough.
The load event can be watched for any element associated with a url, does this not work for you when loading the css stylesheet? http://api.jquery.com/load-event/
Try something like this:
var path = $(this).attr('href');
$('head link').remove();
var styleSheet = $('<link type="text/css" href="'+path+'" rel="stylesheet" />');
styleSheet.load(function(){alert("Loaded");});
$('head').append(styleSheet);
Edit: As pointed out below this only works in IE, who would have thought?
var cssLoaded = function()
{
alert($('body').css('background-color'));
};
$('#theme-selector a').click(function(){
var path = $(this).attr('href');
$('head link').remove();
$('head').append('<link onload="cssLoaded();" type="text/css" href="'+path+'" rel="stylesheet" />');
return false;
});
successfully tested in Chrome 28, IE 10, FF22
You could use lazyload (jQuery plugin) to load a css file.
It has the ability to call a function when the file is included.
Example:
// Load a CSS file and pass an argument to the callback function.
LazyLoad.css('foo.css', function (arg) {
// put your code here
});
Got here looking for a way to remove critical CSS ( element) after being 100% sure, that external sheets have lazyloaded and rendered. This would allow me to use universal, yet visually pleasing critical internal CSS globally over several projects.
Since some of the critical styles go visually against the lazyloaded ones, so they need to be overridden (too much work), or removed. This is what I want, in short:
Load the document with critical internal CSS
Lazyload the additional CSS after the document is rendered and interactive (good for SEO and UX)
Remove critical CSS from HTML after the fancy additional stylesheets have been loaded and truly rendered, to prevent flickering which occured with all other solutions (I have tested this a lot).
A 100% working solution (may it be unpopular) is to use setInterval(); after having the secondary css lazyloaded, to periodically check, whether a style, unique to secondary CSS has truly been applied. Then I can have the critical CSS removed (or whatever I want to do..).
I have created a live demo with comments on Codepen: https://codepen.io/Marko36/pen/YjzQzd and some info in a blogpost: Triggering a Javascript/jQuery event after CSS has loaded.
var CSSloadcheck = setInterval(function () {
if ($('body').css('opacity') != 1) {
//when opacity is set to 0.99 by external sheet
$('style#critical').remove();
clearInterval(CSSloadcheck);
}
}, 100);
You could simply keep on checking if the background colour is still the same, and then do your thing if ever it changes.
oldbackground=getbackground()
function checkbackground(){
if(oldbackground!=getbackground()){
oldbackground=getbackground()
//Do your thing
}
}
setInterval(checkbackground,100)

Categories

Resources