I am trying to target following with jQuery:
<link rel="stylesheet" href="css/test.css">
What I cannot figure out is how to set default path (css folder) ?
<button data-button="test">Just a Test</button>
<script>
var button = $('button'),
link = $('link'),
stylesheet = $(this).data('button');
button.on('click', function() {
console.log(this);
link.attr('href', stylesheet + '.css');
});
</script>
Right now this would change css on button click only if css is in root... So how do I tell him that CSS default path is at "css/".
Trying to find without success.
P.S. One question releated to JS but not to question title.
What is more perferred and correct:
var $something = $('#something');
or
var something = $('#something');
As easy as this
link.attr('href', 'css/' + stylesheet + '.css');
If you want to switch stylesheet, you should use alternate stylesheets instead.
<link rel="alternate stylesheet" href="css/test1.css">
<link rel="alternate stylesheet" href="css/test2.css" disabled>
In jQuery you can then remove/add the disabled property to switch stylesheets:
var links = $("link[rel='alternate stylesheet']");
var button = $("button");
button.on('click', function() {
links.filter(":disabled").prop("disabled", false).siblings().prop("disabled", true);
});
Why don't you simply mention the path css/ in the code itself
link.attr('href', 'css/'+stylesheet + '.css');
To answer to your other question,
var $something and var something are both valid variable names. Your pick.
Related
I've set up a menu to load various stylesheets (which I don't want to edit). What I want to do is set the color of a css class to be the same as the color of navbar-inverse's background-color.
Here's my code so far;
var themes = {
"default": "css/default.bootstrap.min.css",
"theme1": "css/theme1.bootstrap.min.css",
"theme2": "css/theme2.bootstrap.min.css",
"app": "css/app.css"
};
$(function () {
var themesheet = $('<link href="' + themes['default'] + '" rel="stylesheet" />');
themesheet.appendTo('head');
var theColorIs = $('.navbar-inverse').css("background-color");
$('.text-primary2').css('color', theColorIs);
$('.theme-link').click(function () {
var themeurl = themes[$(this).attr('data-theme')];
themesheet.attr('href', themeurl);
var apptheme = $('<link href="' + themes['app'] + '" rel="stylesheet" />');
apptheme.appendTo('head');
var theColorIs = $('.navbar-inverse').css("background-color");
$('.text-primary2').css('color', theColorIs);
});
});
Basically, it loads some bootswatch samples, then reloads my own app.css to override a bunch of things. Then I store the BG color of navbar-inverse to a variable and attempt to set .text-primary2's color to match.
It kind of works but it only changes to the color of the previously selected theme, so if I choose the same one twice then I will eventually catch up.
I can make changes to my app.css, html, or javascript but I'm trying to avoid making changes to individual themes.
I should add that I'm a total novice with regards to jquery, javascript and web development in general.
In my project i am displaying a custom pop up page like below by javascript which has a form for user to fill,then I need to load some js files when pop up is loaded.
how to load js files,plz help.
<html>
<head>
<script type='text/javascript' src='files/jsfiles/core.js'></script>
</head>
<body>
<!- I need to call javascript function showUsers() from here->
<input type='button' onclick='showUsers();' value='listUsers'>
</body>
</html>
function loadScript(src) {
var script = document.createElement("script");
script.async = false;
script.src = src;
document.head.appendChild(script);
};
function loadStyle(src) {
var style = document.createElement("link");
style.rel = "stylesheet";
style.href = src;
document.head.appendChild(style);
};
function loadFiles() {
var scriptsArray = ['src1url', 'src2url'.., 'scrnurl'];
var csssArray = ['src1url', 'src2url'.., 'scrnurl'];
for (var i = 0; i < scriptsArray.length; i++) {
loadScript(scriptsArray[i]);
}
for (var i = 0; i < csssArray.length; i++) {
loadStyle(csssArray[i]);
}
};
function yoursubmitFcn(callback) {
// your functionality here;
callback();
}
$(document).ready(function () {
// do your stuff
yoursubmitFcn(loadFiles);
});
Also check: Another short form
You can use this library fancybox
Loading jQuery from CDN
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css"
media="screen" />
html
Sign in
JS
$('.open_pop').fancybox({
});
function openmsg_sent() {
jQuery(".open_pop").trigger("click");
}
For better and consistent UI, you can use a div which you can display with fixed positioning on click of the button.
I believe Alert wont be able to display css properties if am not wrong.
What you can do is, onclick of the button, in the JS, you can put your popup content into a div which is hidden initially and shown on click.
Hope this helps.
I'm trying this with no success. For reference, the bootstrap slider is here : http://seiyria.github.io/bootstrap-slider/.
I'm not a javascript expert, either, so this might be very simple. The bootstrap-slider site has many examples of how to configure the sliders the way you want them. I'm going to have many sliders generated depending on how many objects are pulled from a JSON file or some other data storing method. It could be 2 or it could be 20.
I created a javascript function called createSlider that I've attempted to pass all of the information required at the bootstrap-slider site. I'm not getting any errors in my Chrome debugging area, but nothing is happening. All of the appropriate client-side sources are loading.
function createSlider (orgId) {
slidersList = document.getElementById('slidersList');
element = slidersList.createElement("div");
var sliderElement = element.createElement('input');
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.setAttribute('id', charityId);
sliderElement.setAttribute('data-slider-id', sliderUnique);
sliderElement.setAttribute('type', 'text');
sliderElement.setAttribute('data-slider-min', '0');
sliderElement.setAttribute('data-slider-max', '100');
sliderElement.setAttribute('data-slider-step', '1');
sliderElement.setAttribute('data-slider-value', '50');
var span = element.createElement('span');
span.setAttribute('style', 'padding-left:5px;');
span.innerHTML =' ';
var innerSpan = span.createElement('span');
innerSpan.setAttribute('id', sliderUniqueVal);
innerSpan.innerHTML = '50';
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.innerHTML = text(slideEvt.value);
});
}
The slider() function is from the external site, and runs fine if I explicitly call it like the examples state to. Anyone know what's going wrong? Is there a better way to do this? Any ideas would be appreciated.
Note, in plain JavaScript, you can only use document.createElement and then append to another HTML element. You cannot call createElement directly against another HTML element.
I changed some of what you wrote from plain old JavaScript into JQuery, and now seems to work:
P.S. Didn't know where charityId came from, so just added it as another parameter into the function.
$(function() {
createSlider('o1','c1');
createSlider('o2','c2');
createSlider('o3','c3');
});
function createSlider (orgId, charityId) {
var slidersList = $('#slidersList');
var element = $("<div></div>").appendTo(slidersList);
var sliderElement = $("<input/>").appendTo(element);
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.attr('id', charityId);
sliderElement.attr('data-slider-id', sliderUnique);
sliderElement.attr('type', 'text');
sliderElement.attr('data-slider-min', '0');
sliderElement.attr('data-slider-max', '100');
sliderElement.attr('data-slider-step', '1');
sliderElement.attr('data-slider-value', '50');
var span = $('<span></span>').appendTo(element);
span.attr('style', 'padding-left:5px;');
span.html(' ');
var innerSpan = $('<span></span>').appendTo(span);
innerSpan.attr('id', sliderUniqueVal);
innerSpan.html('50');
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.text(slideEvt.value);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type='text/javascript' src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://seiyria.github.io/bootstrap-slider/stylesheets/bootstrap-slider.css">
<script type='text/javascript' src="http://seiyria.github.io/bootstrap-slider/javascripts/bootstrap-slider.js"></script>
<div id="slidersList"></div>
What would be the easiest way with regex to extract the href string containing a stylesheet link and save it to a variable in JavaScript?
The stylesheet is a string and not a real stylesheet link. It's intended to be inserted with Javascript after the page loads.
EDIT:
<script>
// Loading stylesheet just before body closes
$(function() {
var stylesheet = '<link href="/Static/css/compiled/styles.css" rel="stylesheet"/>';
var stylesheetHref = ""; // WANT TO SET THIS!!
if (document.createStyleSheet) {
document.createStyleSheet(stylesheetHref);
} else {
$("head").append(stylesheet));
}
});
</script>
Why not create elements the proper way and just start out with the href in a variable ?
$(function () {
var href = '/Static/css/compiled/styles.css';
var stylesheet = $('<link />', {rel: 'stylesheet', href: href});
$("head").append(stylesheet);
});
If you have a stylesheet link in string format then this will get you the href value, very easily without regex...
var link = '<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/stackoverflow/all.css" />';
var href = $(link).attr("href");
Try this:
<script>
// Loading stylesheet just before body closes
$(function() {
var stylesheet = '<link href="/Static/css/compiled/styles.css" rel="stylesheet"/>';
var stylesheetHref = stylesheet.replace(/.*href="(.*?)".*/i, "$1");
if (document.createStyleSheet) {
document.createStyleSheet(stylesheetHref);
} else {
$("head").append(stylesheet));
}
});
</script>
I'm using a JS CSS switcher to good effect really brilliant. However, I would be delighted if it worked more seamlessly. At the point of opening a new page on the site the default css style often flickers on breifly, before the cookie re-applies the selected CSS style.
e.g. the canvas style is the default style, this opens when first visiting the site, user selects corporate style, they open another page in the site - the canvas style shows for a split second, then the corporate style loads over it. Worse on older computers, but on my main computer this does not often happen on Firefox, although on other browsers, especially Chrome its very noticeable. Does anyone have the expertise to update the workings below with a tweak to say, first check for the cookie, then if no cookie, apply the default style, rather than applying the default style seemingly at the same time?
the code I am using is here below:
in html head:
<script type="text/javascript">
$(function()
{
// Call stylesheet init so that all stylesheet changing functions
// will work.
$.stylesheetInit();
// This code loops through the stylesheets when you click the link with
// an ID of "toggler" below.
$('#toggler').bind(
'click',
function(e)
{
$.switcher();
return false;
}
);
// When one of the styleswitch links is clicked then switch the stylesheet to
// the one matching the value of that links rel attribute.
$('.styleswitch').bind(
'click',
function(e)
{
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
}
);
</script>
<link rel="stylesheet" type="text/css" href="/css/canvas.css " title="canvas">
<link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">
<link rel="alternate stylesheet" type="text/css" href="/css/earth.css " title="earth">
<link rel="alternate stylesheet" type="text/css" href="/css/space-and-stars.css " title="space-and-stars">
<link rel="alternate stylesheet" type="text/css" href="/css/under-the-sea.css " title="under-the-sea">
<link rel="alternate stylesheet" type="text/css" href="/css/classical.css " title="classical">
<link rel="alternate stylesheet" type="text/css" href="/css/creative.css " title="creative">
the JS
(function($)
{
// Local vars for toggle
var availableStylesheets = [];
var activeStylesheetIndex = 0;
// To loop through available stylesheets
$.switcher = function()
{
activeStylesheetIndex ++;
activeStylesheetIndex %= availableStylesheets.length;
$.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
};
// To switch to a specific named stylesheet
$.stylesheetSwitch = function(styleName)
{
$('link[#rel*=style][title]').each(
function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) {
this.disabled = false;
activeStylesheetIndex = i;
}
}
);
createCookie('style', styleName, 365);
};
// To initialise the stylesheet with it's
$.stylesheetInit = function()
{
$('link[rel*=style][title]').each(
function(i)
{
availableStylesheets.push(this.getAttribute('title'));
}
);
var c = readCookie('style');
if (c) {
$.stylesheetSwitch(c);
}
};
}
)(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name,"",-1);
}
// /cookie functions
I would do it server-side...
Anyway, when you do
$(function()
{
});
jQuery waits until the DOM is fully load to execute the function.
So, you should place the javascript just below the <link />s section, outside $(function(){}); . This will make the script as soon as the browsers parses it, and before the page is fully loaded. (it has to be below the elements because they must be loaded)
I think you might wish to run your code before the DOM is ready. Perhaps you could run it immediately rather than using $(function(){...}), since jQuery waits until the page loads to execute anything in that (hence the flicker).
Also perhaps this might give insight.
http://forum.jquery.com/topic/use-jquery-before-the-dom-is-ready-12-1-2010
Debugging steps for why links are not working:
>>> $('link[#rel*=style][title]') --> seems to show your styles are there
[..., <link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">, ...]
>>> $.stylesheetSwitch('corporate') --> seems to work
The only problem is that the links are not having anything bound to the onclick; wait... don't you mean this.getAttribute('title')? as you can see above, rel="alternate stylesheet" which is probably not your intent to use as a unique theme identifier.