adding css file with jquery - javascript

I am creating a popupwindow and I want to add a css file to that popupwindow. Below is the code for popupwindow. I have a JavaScript which creates a popupwindow.
Print1
Now I want to add a css file to this popupwindow. I tried something like
$('.popupwindow').append('<link rel="stylesheet" href="css/style2.css" type="text/css" />');
$('head').append('<link rel="stylesheet" href="css/style2.css" type="text/css" />');
but it doesn't work.

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
This should work.

This is how I add css using jQuery ajax. Hope it helps someone..
$.ajax({
url:"site/test/style.css",
success:function(data){
$("<style></style>").appendTo("head").html(data);
}
})

var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
});
css_link.appendTo('head');

Just my couple cents... sometimes it's good to be sure there are no any duplicates... so we have the next function in the utils library:
jQuery.loadCSS = function(url) {
if (!$('link[href="' + url + '"]').length)
$('head').append('<link rel="stylesheet" type="text/css" href="' + url + '">');
}
How to use:
$.loadCSS('css/style2.css');

Try doing it the other way around.
$('<link rel="stylesheet" href="css/style2.css" type="text/css" />').appendTo('head');

Your issue is that your selector is for an anchor element <a>. You are treating the <a> tag as if it represents the page which is not the case.
$('head') will work as long as this selector is being executed by the page that needs the css.
Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.
ADDENDUM to your reasoning:
Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.

I don't think you can attach down into a window that you are instancing... I KNOW you can't do it if the url's are on different domains (XSS and all that jazz), but you can talk UP from that window and access elements of the parent window assuming they are on the same domain. your best bet is to attach the stylesheet at the page you are loading, and if that page isn't on the same domain, (e.g. trying to restyle some one else's page,) you won't be able to.

Have you tried simply using the media attribute for you css reference?
<link rel="stylesheet" href="css/style2.css" media="print" type="text/css" />
Or set it to screen if you don't want the printed version to use the style:
<link rel="stylesheet" href="css/style2.css" media="screen" type="text/css" />
This way you don't need to add it dynamically.

Related

javascript: window.location automatically changed included links

I've used window.location (.assign, .replace, .href) to redirect to a page product on click. But for some reason it automatically changes some of href links.
For example:
previous href="commercial/fonts/fonts.min.css" is now href="product/commercial/fonts/fonts.min.css".
previous HTML file
<link rel="stylesheet" type="text/css" href="commercial/fonts/fonts.min.css" />
After this click event triggers
$('.productImage').on('click', function(){
var product_id = $(this).data('id');
window.location.assign("/product/"+product_id);
});
New HTML
<link rel="stylesheet" type="text/css" href="product/commercial/fonts/fonts.min.css" />
Product is automatically to the href. This happens with some other files as well. In case of img src as well
Use / at the beginning of your href, like so: href="commercial/fonts/fonts.min.css" - that should make the URL relative to your document root. At the moment you're using a URL that is relative to the current document. You may want to read up on absolute vs relative URLs, eg in this answer.

How to change stylesheet with Jquery and Django

Hello I've been trying to solve this problem for quite a while. Back when I was using vanilla html this code seems to work. (Changing from tile view to list view). Now that I have incorporated it in django and the hrefs contains static tags, I dont know how to refer to it in jquery and change its href. Pls help
HTML
<link rel="stylesheet" type="text/css" href="{% static "Stylesheets/tileVersion.css" %}">
I want to change it to this css href
<link rel="stylesheet" href="../Stylesheets/listVersion.css">
JQUERY
$('#listicon').click(function () {
$('link[href="static/Stylesheets/tileVersion.css"]').attr('href', 'static/Stylesheets/listVersion.css');
});
$('#tilesicon').click(function () {
$('link[href="static/Stylesheets/listVersion.css"]').attr('href', 'static/Stylesheets/tileVersion.css');
});
I want to be able to switch between them if possible. Any kind of help would be appreciated
You can do one of two things.
You can use static references to load one CSS file over another, by using a if tag in your code getting the css link value (the address/url) from a variable or from a data source. This compiles during server time. This also means that only one css is loaded at runtime. This is static for the client. For example:
Same as #1, but you can use an inline if to determine which one goes forward to the client.
Lastly, ensure both css files are held within the static process, and maintain your jquery:
$('#listicon').click(function () {
$('link[href="{% static /path/to/first/css/page %}"]').attr('href', '{% static /path/to/first/css/page %}');
});
$('#tilesicon').click(function () {
$('link[href="{% static /path/to/second/css/page %}"]').attr('href', {% static /path/to/second/css/page %});
});
I typed this out of memory, so please bear with me.
Hope this helps.
Just put an additional attribute id for the link tag. You can remove the current stylesheet from head and add another one.
<link rel="stylesheet" id="myid" href="../Stylesheets/listVersion.css">
$('#myid').remove();
$('head').append( $( '<link/>', {'rel' : 'stylesheet', 'id': 'myid', 'href':'newlink' } ));

Change entire CSS file on refresh

All other questions I've found relating to this are about changing specific elements, or changing the CSS file with a button, but what I'm looking to find out is:
Is there a script that will swap an entire CSS file whenever the page is refreshed?
I.e. I've got my core style.css and supplementary {color}.css files which replace certain elements in style.css, and I'd like those supplementary CSS files to be loaded randomly on refresh.
Sorry, I don't even know where, to begin with this. Hopefully, someone can offer some pointers?
Thank you.
Fundamentally this is just a matter of picking something at random, e.g.:
<head>
<!-- ... -->
<script>
var sheets = ["sheet1.css", "sheet2.css", "sheet3.css"];
var sheet = sheets[Math.floor(Math.random() * sheets.length)];
document.write('<link rel="stylesheet" href="' + sheet + '">');
</script>
<noscript>
<link rel="stylesheet" href="sheet1.css">
</noscript>
<!-- ... -->
(One of the rare cases where document.write isn't actually a bad solution.) Note the noscript fallback will always use the same stylesheet on browsers with JavaScript disabled.
All you need to do to load a CSS-file with Javascript is to add a <link> element to the DOM/body and it will be loaded automatically.
So in your <head> section you could include a <script> tag that just randomly selects a color.css from an array and generate the link tag, preferably as early as possible in the file to prevent flickering.
<script>
var colors = ['red.css', 'blue.css', 'green.css'];
var colors_idx = Math.floor(Math.random()*colors.length);
document.write('<link href="'+colors[ colors_idx ]+'" rel="stylesheet" type="text/css" />');
</script>
(PS. There are cleaner ways to inject HTML, keeping it concise to focus on the solution. Use your favorite approach, document.write can be a bit fickle.)

How do I reference a javascript variable from a razor section?

I'm trying to dynamically render a CSS file to my view, but part of the location of the file is in a javascript variable.
Currently I have:
#section Styles {
#{
<link href="#Url.Content(Model.CssPath)" rel="stylesheet" type="text/css" />
}
}
But I need to include the variable in the path, like this:
#section Styles {
#{
var pathPrefix = "somePath/";
<link href="#Url.Content(pathPrefix + Model.CssPath)" rel="stylesheet" type="text/css" />
}
}
I understand the server-side code is evaluated before the javascript variable exists, so how else do I accomplish this?
First of all - why mixing client-side/server-side code?
You cannot use JS variable along with server-side generated content because - as you said - it is executed on server before client's browsers hits JS code. This is expected behavior.
If this variable value can be determined on the server-side, you should move it there.
If it has to be generated on the client side, you can generate <link> tag using document.createElement('link'); but it seems odd to me :)
Rather than trying to add the stylesheet via the razor view I would put the csspath into a javascript variable and then use jquery to combine it with the pathPrefix and append the stylesheet that way.
something like....
<script>
var cssPath = #Model.cssPath;
var pathPrefix = "www.";
$('head').append('<link rel="stylesheet" type="text/css" href="'+pathPrefix+cssPath+'">');
</script>

Css fallback when JavaScript is disabled

With jQuery Mobile, I use this snippet to call libaries...
<script src="//code.jquery.com/jquery-1.6.4.min.js"></script>
<script>
if(typeof jQuery === 'undefined')
{
document.write(unescape('%3Cscript src="js/jquery-1.6.4.min.js"%3E%3C/script%3E'));
document.write(unescape('%3Cscript src="jqm/jquery.mobile-1.1.0.min.js"%3E%3C/script%3E'));
document.write(unescape('%3Clink rel="stylesheet" href="jqm/jquery.mobile-1.1.0.min.css"%3E%3C/script%3E'));
document.write(unescape('%3Clink rel="stylesheet" href="jqm/jquery.mobile.structure-1.1.0.min.css"%3E%3C/script%3E'));
}
else
{
document.write(unescape('%3Cscript src="//code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"%3E%3C/script%3E'));
document.write(unescape('%3Clink rel="stylesheet" href="//code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css"%3E%3C/script%3E'));
document.write(unescape('%3Clink rel="stylesheet" href="//code.jquery.com/mobile/1.1.0/jquery.mobile.structure-1.1.0.min.css"%3E%3C/script%3E'));
}
</script>
But if JavaScript is disabled, how to call stylesheets?
If I use (I'm a bit stupid!)...
<noscript>
<link rel="stylesheet" href="jqm/jquery.mobile-1.1.0.min.css" />
<link rel="stylesheet" href="jqm/jquery.mobile.structure-1.1.0.min.css" />
</noscript>
... My page is blank.
Thanks for your help.
Vincent
The Modernizr approach is to use JavaScript to add a class called "js" to the HTML tag on load, and remove a class called "no-js" which (in this case) you add yourself.
Now, you can add some CSS styles only to descendants of .js and others only to descendants of .no-js, customizing either one to your liking.

Categories