javascript: window.location automatically changed included links - javascript

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.

Related

Setting href for .less stylesheet through JS

I'm using cookies to find out if the user is in light or dark mode onload of body. I always use the light.less as the fallback/default if a cookie can't be found. So in my <head> I have
<link rel="stylesheet" type="text/css" href="../assets/main.css">
<link rel="stylesheet/less" type="text/css" id="colorMode" href="../assets/light.less">
<script src="../assets/less.js/dist/less.min.js" type="text/javascript"></script>
and my body tag is as follows:
<body onload="checkNav(); checkCookies();" onresize="checkNav()">
The checkCookies() is the function to review the cookie and act accordingly, it is shown below.
function checkCookies() {
var style = getCookie("style");
if (style == 'dark') {
document.getElementById("colorMode").href = "../assets/dark.less";
document.getElementById("switchIcon").innerHTML = "toggle_on";
document.cookie = "style=dark; path=/~sam.walker";
}
else {
//Already set by default
}
}
The getCookie() function simply returns the relevant style cookie
The colorMode stylesheet with href = ../assets/light.less does change as expected to ../assets/dark.less as I've checked with inspector but the style itself does not physically change. I've checked cache and its nothing to do with that. Any help would be greatly appriciated.
Including the stylesheet as a .less format won't work unless you have <script src="less.js" type="text/javascript"></script> added within the <head> section of your page.
Check out the usage information from Less.js here
less.min.js will find references to LESS files and generates CSS from them when it loads.
You are creating a new reference to a LESS file after that, by which time it is too late for less.js to notice.
You need to call checkCookies(); after you have linked to the LESS stylesheet but before you load the less.js script.
Thanks for your help,
Through your info I have found the following (botch) fix:
var elem = document.getElementById('NameOfOriginalLessGeneratedStyle'); //REQUIRES CHANGE ON SERVER CHANGE
elem.parentNode.removeChild(elem);
//Deleted previous styles
less.refresh();
//Loads new style
Should run after stylesheet href change.

Appending Stylesheet via javascript without flickering

I have a default CSS code for my page. I am injecting a CSS stylesheet file into the bottom of the head that overrides the default one using JavaScript. For some reason when I load the page, I see the default one and then it overrides it with the loaded stylesheet,
What can I do so that flickering will not occur? I thought that if I add a CSS at the end of the head after the default one I won't see the flickering because the content is not loaded yet, but apparently, it is. Any solution for that?
I don't know if flickering is the right word, I just see the default CSS and immediately after I see the page with the overridden CSS. Furthermore, maybe it's relevant, the overridden CSS only overrides some of the elements not all of them.
Here is the code:
<head>
<link href="/Content/app.min.css?ver=17" rel="stylesheet" />
<script>
// dark theme
if (localStorage.getItem("current_theme") === "dark") {
var head = document.head,
link = document.createElement('link');
link.type = 'text/css',
link.rel = 'stylesheet',
link.href = '/Content/dark_theme.min.css?r=' +
(Math.floor(Math.random() * 20000) + 1);
head.appendChild(link);
}
</script>
// the JavaScript appended stylsheet will render here before the </head> element
</head>
What happens is that the change of the new CSS happens only after the page has been loaded. I put a breakpoint in the footer, and only after the page is loaded I see the new CSS update.
I've found out that this happens because the stylesheet file is loaded asynchronously and therefore the delay. I need to inject the CSS code inline to make it work. The problem is with that approach is that it adds 9KB to each page call instead of dynamically based on the localStorage variable value.
The following code works faster:
<head>
<link href="/Content/app.min.css?ver=17" rel="stylesheet">
<script>
// dark theme
if (localStorage.getItem("current_theme") === "dark")
document.head.innerHTML += '<link rel="stylesheet" href="/Content/dark_theme.min.css">';
</script>
</head>
But your approach is wrong.
You'd better use a cookie for this stuff. Save the theme name to the cookie. Read cookie from request headers and include the required css right on the server side. So the client receives:
<head>
<link href="/Content/app.min.css?ver=17" rel="stylesheet">
<link rel="stylesheet" href="/Content/dark_theme.min.css">
</head>
Also I'd recommend setting correct Expires headers on the server and getting rid of ugly ?ver=17 or ?r=(Math.floor(Math.random() * 20000) + 1)

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' } ));

ASP.NET MVC Inserting CSS file in header via JavaScript depending on screen size

Im working on a MVC3 application, with a masterpage which renders the views in the body.
Now I have 2 css files (different layouts), and I want to select the CSS depending on the screen size of the client.
Everything works with the code below, however, only for the index page, whenever I go to a second page, whatever it is, no CSS is rendered at all.
The code below is placed in the HEAD section of the masterpage.
<script type="text/javascript">
var css = './Content/SiteWide.css'
if ($(window).width() < 1140) {
css = './Content/SiteNarrow.css';
}
var tempcss = '<link href="TEMPCSS" rel="stylesheet" type="text/css" />';
var cssLink = tempcss.replace("TEMPCSS", css);
document.write(cssLink);
</script>
So somehow the css doesnt load again when you go to a second page (all using the same masterpage), do you guys have any ideas?
thanks
Use CSS media queries instead of Javascript.
<!-- dropped rel attribute -->
<link media="only screen and (max-width:1139px)" href="SiteNarrow.css" />
<link media="only screen and (min-width:1140px)" href="SiteWide.css" />
Ideally you create one CSS file for one state, and have another override that when conditions are met.
<!-- dropped rel attribute -->
<link href="base.css" />
<link media="only screen and (min-width:1140px)" href="override.css" />
I believe you need to use Url.Content(). I.e.
#Url.Content("~/Content/SiteWide.css");
The pathing may be incorrect when you navigate from your Index page if you use
./Content/SiteWide.css
I've usually found Url.Content() to be the right thing to do when pathing to files in the project
Pro-tip: Don't use static file locations. Make use of Url.Content.
Your code would look like:
var css = '#Url.Content("~/Content/SiteWide.css")';
Try this out and see if it works. From experience I've had static locations sometimes not work as expect, whereas Url.Content did the trick for me.
I recommend implementing Responsive Web Design
http://www.sitepoint.com/responsive-web-design/#fbid=UhFHwQrRwnn
You can use what are called "Media Queries" to dynamically apply different css files or properties as the screen size changes, in real time. Very cool!

adding css file with jquery

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.

Categories