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>
Related
I have been looking around here, and found ways to toggle between 2 css files, but not more files than that. I need to use 1 button to alternate between 4 different files. My main css that is loaded with the html is called style1.css.
I found a js snippet that does this with images, and what it does is put all the images in an array, and take the first object out of and places it last in the array. I have been able to make this work:
var imageUrls = ["images/paulfr.jpg", "images/johnfr.jpg",
"images/georgefr.jpg", "images/ringofr.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
Now, I tried remaking it for stylesheet files, but it fails:
var stylesUrls = ["css/style1.css", "css/style2.css",
"css/style3.css", "css/style4.css"];
function changeStylesheet(){
var style = document.getElementById('styles');
var stylesUrl = stylesUrls.shift();
style.src = stylesUrl;
stylesUrls.push(stylesUrl);
}
I did make sure that stylesheet id is 'styles'. Could somebody please show me where I go wrong?
change src to href:
style.src = stylesUrl;
to
style.href = stylesUrl;
Full solution:
var stylesUrls = ["css/style1.css", "css/style2.css",
"css/style3.css", "css/style4.css"];
window.onload = function(){
var refButton = document.getElementById("change-styles");
refButton.onclick = function() {
var style = document.getElementById('styles');
var stylesUrl = stylesUrls.shift();
style.href = stylesUrl;
stylesUrls.push(stylesUrl);
}
};
HTML
<link href="css/style1.css" rel="stylesheet" id="styles" type="text/css">
Change
I want to convert an anchor that contains .pdf in the href with embed tag and href into src
Hello this is test
This need to be changed in embed tag: as below output
<embed src="www.google.com/pdf">
To achieve this use replaceWith(). Provide a function to the method call which returns the new content, like this:
$('a').replaceWith(function() {
return `<embed src="${this.href}" />`;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hello this is test
Note that you need to include the protocol in the absolute URL. Beginning it with www will not work.
Simply replace the outerHTML.
$('a').each(function () {
if (this.href.indexOf('pdf')) { // checks whether href contains pdf
this.outerHTML = "<embed src=" + this.href + ">";
}
});
Here's a pure JavaScript solution for when you don't want jQuery:
const a = document.querySelector('a');
const e = document.createElement('embed');
e.setAttribute('src', a.href)
const aParent = a.parentElement;
const aNextSibling = a.nextElementSibling;
if (aNextSibling) {
aParent.insertBefore(e, aNextSibling);
} else {
aParent.appendChild(e);
}
a.remove();
Do you know how to load a random css without refreshing the page?
I would like to load a random style like the one achieved in this thread:
<script>
var link = [];
link[0] = "css/0.css";
link[1] = "css/1.css";
link[2] = "css/2.css";
link[3] = "css/3.css";
$(function() {
var style = link[Math.floor(Math.random() * link.length )];
if (document.createStyleSheet){
document.createStyleSheet(style);
}else{
$('<link />',{
rel :'stylesheet',
type:'text/css',
href: style
}).appendTo('head');
}
});
</script>
This code works, but is it possible to load another style randomly every 5 seconds without refreshing?
Thanks a lot.
Use setInterval() to do it every 5 seconds and use 'document.createElement` to create the new link.
You must also remember to remove the previously created link before adding the new one.
function getLink(){
// Find previous <link> (if exists) and remove it
var prevLink = document.querySelector("head > link");
if(prevLink) {
document.querySelector("head").removeChild(prevLink);
}
// Get a random CSS link
var style = links[Math.floor(Math.random() * links.length )];
// Create a new <link> element and configure it
var link = document.createElement("link");
link.setAttribute("href", style);
link.setAttribute("rel", "stylesheet");
console.log(link);
// Inject element into the DOM
document.querySelector("head").appendChild(link);
// Once the stylesheet has finished downloading, add it to the DOM
link.addEventListener("load", function(){
// Now that the new stylesheet has been applied, wait 5 seconds and
// then replace it again:
setTimeout(getLink, 5000);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div i="styleMe">I'm being randomly styled.</div>
Maybe somewhere in the vicinity of this...
var links = ["css/0.css", "css/1.css", "css/2.css", "css/3.css"];
function setCSS(){
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = links[ Math.floor(Math.random()*links.length) ];
document.head.link && document.head.link.remove();
document.head.link = link;
document.head.appendChild(link);
}
setInterval(setCSS,5000);
setCSS();
There could be a delay while new <link> loads; if that is issue you can use Promise to wait until new <link> is loaded before calling loadCSS() again
var link = ["0.css", "1.css", "2.css", "3.css"];
$(function() {
function loadCSS() {
return new Promise(function(resolve) {
$("link:not(:last)").remove();
var style = link[Math.floor(Math.random() * link.length)];
var css = $('<link />', {
rel: 'stylesheet',
type: 'text/css',
href: style
})
.on("load", function() {
setTimeout(function() {
resolve(css)
}, 5000)
})
.appendTo('head');
})
.then(function() {
return loadCSS()
})
}
loadCSS()
});
http://plnkr.co/edit/yUEJXh1szCAGB9s7VqvM?p=preview
I need to change image when I click on it every time.
I added full path even it's not working.
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
if (imageon.src=="play1.gif"){
imageon.src="shutdown.png";
}
else if (imageon.src== "shutdown.png") {
imageon.src="play1.gif";
}
};
</script>
<img src="shutdown.png" id="myElement" onclick="changeImage();" style="width:95px"></img>
Javascript:
var pullImage=document.getElementById("change");
function changeImage(){
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif") {
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png";
};
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png"){
pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif";
}
};
The problem is your path. I recreated the problem and i alerted the actual source which look like this:
You will either have to give the actual full path. Or you dont use the path as refrence, but a html reference. For example a hidden div with value 1 or 2 - for the used image
<div id="imgnumber">1</div>
<script>
var imagediv = document.getElementById("imgnumber");
var imageon= document.getElementById("myImg");
function changeImage(){
if (imagediv.innerHTML == "1"){
imageon.src="b.png";
imagediv.innerHTML = "2";
}
else if (imagediv.innerHTML == "2") {
imageon.src="a.gif";
imagediv.innerHTML = "1";
}
};
</script>
Please use below javascript and place it anywhere below tag you are using
<script type="text/javascript">
var imageon= document.getElementById("myElement");
function changeImage(){
var filename = imageon.src.replace( /^.*?([^\/]+)\..+?$/, '$1' );
if (filename=="play1"){
imageon.src="shutdown.jpg";
}
else if (filename== "shutdown") {
imageon.src="play1.jpg";
}
};
</script>
Using attr function you can change src of image :
$("#my_image").attr("src","second.jpg");
You can also create event eg. put thumbnail and on clicking load original image:
$('#my_image').on({
'click': function(){
$('#my_image').attr('src','second.jpg');
}
});
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.