how to replace backgrund url in css class using regexp (javascript) - javascript

I have an html string in which I want to replace url of background-image. But wasn't able to do it.
This code looks like html but actually its a string which have html data.
MY string
var html ="
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}"
I want to replace the url after the .reg-left.
I applied this regex but it will replace first one.
html.replace(/url\((['"]?)(.+?)\1\)/, "url(" + replacableImage + ")");

Your HTML string is not HTML. It is CSS.
Your regex works. You need to add a g to get all of them
Also you cannot have newlines in a JS string - you need backticks to allow the linefeeds
const replacableImage = "abc.jpg";
let CSS =`
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}`
CSS = CSS.replace(/url\((['"]?)(.+?)\1\)/g, "url(" + replacableImage + ")")
console.log(CSS)
If you only want one of them, you can run a replace function or a split+map+join
const replacableImage = "abc.jpg";
let CSS = `
.reg-inner {
background-image: linear-gradient),url(http:\\abc.com);
}
.reg-left {
background-image: linear-gradient),url(http:\\abc.com);
background-size: cover;
}
.reg-right {
background-image: linear-gradient),url(http:\\abc.com);
}`
CSS = CSS.split('.reg-').map(
str => str.indexOf('left') === 0 ?
str.replace(/url\((['"]?)(.+?)\1\)/, `url("${replacableImage}")`) : str
)
.join('.reg-')
console.log(CSS)

Related

How to change multiple backgrounds in a Javascript file?

I have designed a game where In the first page I ask the name of the user( background used- bgimg1)
On the click of a certain button, I go to the next page(I changed the background again) What I tried to do this was background(bgimg2) and I also tried putting [changeImage and changeAnimation, no error and still did not work], so I tried putting bgimg = bgimg2, It worked!
Now I displayed another button, and on the click of the button I called a function (name - attack),
In the function I tried to use bgimg2 = bgimg3;
It did not work, what should I do to change the background again, please suggest how to change the background, I think maybe if I preload all the images in the same variable, then how will I display different backgrounds in different functions;
Code
function preload() {
bgimg = loadImage("images/LayoutGH.png");
bgimg2 = loadImage("Screen 1/image.jpg");
bgimg3 = loadImage("Attack/attackButtonbg.jpg");
}
Simply use a css class with each images, and change on your command
(function ()
{
const bgClass = [ 'bg1', 'bg2', 'bg3' ]
, btChange = document.getElementById('bt-bg')
;
let noBg = 0;
document.body.className = bgClass[noBg];
btChange.onclick=_=>
{
noBg = ++noBg %3;
document.body.className = bgClass[noBg];
}
})();
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
.bg1 { background-image: url(https://picsum.photos/id/251/500/300.jpg); }
.bg2 { background-image: url(https://picsum.photos/id/259/500/300.jpg); }
.bg3 { background-image: url(https://picsum.photos/id/254/500/300.jpg); }
<button id='bt-bg'> change </button>

Change background with button

I am trying to make it so that when the user clicks on a restyle button it will change the background to the images stored in my folder. I have a couple, and then you can choose to reset back to the normal image, however for some reason I cant get it to work, any help would be great on this matter:
HTML buttons
ReStyle
Reset
Javascript
var counter = 0;
function changeLook(){
counter += 1;
switch (counter) {
case 1:
document.body.style.backgroundImage = "../Image/BackgroundImage2.jpg";
break;
case 2:
document.body.style.backgroundImage = "../Image/BackgroundImage3.jpg";
break;
case 3:
counter = 0;
document.body.style.backgroundImage = "../Image/BackgroundImage4.jpg";
break;
}
}
function changeBack(){
document.body.style.backgroundImage = "../Image/BackgroundImage1.jpg";
}
CSS
body {
padding-top: 23px;
padding-bottom: 10px;
background: url('../Image/BackgroundImage1.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Just add url(image path) like:
document.body.style.backgroundImage = "url(../Image/BackgroundImage2.jpg)";
var counter =0;
function changeLook() {
counter += 1;
switch (counter) {
case 1:
document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
break;
case 2:
document.body.style.backgroundImage = "url(http://placehold.it/300x300)";
break;
case 3:
counter = 0;
document.body.style.backgroundImage = "url(http://placehold.it/400x400)";
break;
}
}
function changeBack(){
document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
}
body {
padding-top: 23px;
padding-bottom: 10px;
background: url('http://placehold.it/200x200') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
ReStyle
Reset
It's likely that you're referencing your file paths incorrectly. Check your developer console within your browser. Do you see any 404 errors?
Additionally, you can simplify your changeLook function by using a modulus:
var counter = 1;
function changeLook(){
counter = counter % 4 + 1;
document.body.style.backgroundImage = "../Image/BackgroundImage" + counter + ".jpg";
}
function changeBack() {
document.body.style.backgroundImage = "../Image/BackgroundImage1.jpg";
}
You absolutely could use your current code. If it isn't working, then the issue is likely that your relative paths within your CSS files for your background properties are incorrect.
It's important to remember that the paths used within a CSS file will be relative to the CSS file itself and not where it is referenced. However, when you use the relative references in your Javascript code, it will be made relative to where the Javascript is referenced (i.e. your HTML document).
You may want to consider defining CSS styles to handle these changes :
body.background1 {
background: url('../Images/Image1.jpg');
}
body.background2 {
background: url('../Images/Image2.jpg');
}
/* Continue as necessary */
And then simply update the class for your <body> element using Javascript :
// Use the counter to determine which style to apply
switch (counter) {
case 1:
document.body.className = "background1";
break;
case 2:
document.body.className = "background2";
break;
case 3:
counter = 0;
document.body.className = "background3";
break;
}
Example
You can see a very basic example of this here and demonstrated below :

Is there a way to access a JavaScript String variable in the CSS part of the HTML?

Is there a way to access a JavaScript String variable in the CSS part of the HTML?
For example, I've got a prefix that keeps occuring in all image URLs. It would only be proper to set a common variable with the prefix, for code maintenance. I'm looking for something like this:
<script type="text/javascript">
var dropBoxPrefix = 'https://dl.dropboxusercontent.com/s/XXXX';
</script>
<style>
html, body {
background-image: url(dropBoxPrefix + '/bg.gif');
}
.re {
background-image: url(dropBoxPrefix + '/header-bottom-left.png');
}
ul li {
background-image: url(dropBoxPrefix + '/ok.png');
}
.networksTtl {
background-image: url(dropBoxPrefix + '/Maps.png');
}
</style>
If you decide to go the LESS way, ( and could use the simpLESS compiler : example write code in filename background.less then drag and drop it into the simpleLess compiler and will get converted to background.css
LESS Code:
//variables
#dropBoxPrefix : 'https://dl.dropboxusercontent.com/s/XXXX/';
#imageHTML : "bg.gif";
#imageRe : "header-bottom-left.png";
#imageULLI : "ok.png";
#imageNetworksTtl : "Maps.png";
//mixin
.backgroundImage(#image){
#bi : "#{dropBoxPrefix}#{image}";
background-image: url(#bi);
}
//styles
html, body{
.backgroundImage(#imageHTML);
}
.re{
.backgroundImage(#imageRe);
}
ul li{
.backgroundImage(#imageULLI);
}
.networksTtl{
.backgroundImage(#imageNetworksTtl);
}
you will receive compiled CSS:
html,
body {
background-image: url("https://dl.dropboxusercontent.com/s/XXXX/bg.gif");
}
.re {
background-image: url("https://dl.dropboxusercontent.com/s/XXXX/header-bottom-left.png");
}
ul li {
background-image: url("https://dl.dropboxusercontent.com/s/XXXX/ok.png");
}
.networksTtl {
background-image: url("https://dl.dropboxusercontent.com/s/XXXX/Maps.png");
}
No it is not possible in your way, but you can set this style property during js script execution
document.body.style.backgroundImage = "url('https://dl.dropboxusercontent.com/s/XXXX/bg.gif')";
http://www.w3schools.com/jsref/prop_style_backgroundimage.asp
No way but a turnover could be to add styles in your head section with javascript, like this (jQuery example) :
var color1 = 'green';
$('<style>.yourclass { color:' + color1 +'}</style>').appendTo('head');
in pure js :
var color1 = 'green';
var css = '.yourclass { color:' + color1 +'}',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

Having a specific background image for each and every list item

Was wondering if there was a way to condense this and have it go on
li:nth-child(1){
background-image: url(1.jpg);
}
li:nth-child(2){
background-image: url(2.jpg);
}
li:nth-child(3){
background-image: url(3.jpg);
}
li:nth-child(4){
background-image: url(4.jpg);
}
li:nth-child(5){
background-image: url(5.jpg);
}
And so on and so on.
Would there be a way to have this go on with pure css variables or is there an easier solution with javascript?
CSS has no way to relate, as yet, the index of the element to a property of that element's CSS; with JavaScript it's easy enough:
var liElements = document.querySelectorAll('li');
[].forEach.call(liElements, function (li, index) {
li.style.backgroundImage = 'url(' + index + '.jpg');
});
With CSS it's possible, in future, that the following may work (but this is pure speculation):
ul {
counter-reset: liCount;
}
ul li {
counter-increment: liCount;
background-image: url(counter(liCount) '.jpg');
}
This does not work in any current browsers, and may never work in any browser. As noted, this is purely speculative.
If you don't know how many children you have, you'll want to use JS. Or, if you do, but don't want to type it all out, or have a max, then PHP which could just make the CSS file which would be faster than JS doing it after the load.
var liElems = document.getElementsByTagName('li');
for(var i = 0; i < liElems.length(); ++i){
li.style.backgroundImage = 'url("' + i + '.jpg")';
}
Or, for PHP:
for($idx = 0; $idx < MAGIC_NUM; ++$idx){
print("li:nth-child($idx){");
print(" background-image: url($idx.jpg);")
print("}\n");
}

Trying to change a background image on page refresh, running into problems

To begin, here is the page.
I've attempted the Javascript code without success, so I will try to explain my current setup.
my body has an ID of #homepage. This is the only page I will need this code for, so I've assigned that ID. The following is the CSS to access the image and cover the page:
body#homepage {
background-attachment: fixed;
background-image: url(../images/bg/4.jpg);
background-repeat: no-repeat;
background-position: center bottom;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
There are 4 images in the "../images/bg" folder, numbered 1 through 4. I simply want the images to change between the 4 upon page load, but I need to keep the images styled as they are in the current CSS.
Since I am only vaguely familiar with Javascript, I believe I'm getting something very simple wrong in the Javascript. I would appreciate someone spelling this out for me in specific detail. Thanks so much!
try this
var randomImage = Math.floor((Math.random()*4)+1);
var homePage = document.getElementById('homepage');
homePage.style.backgroundImage='url("..\/images\/bg\/'+randomImage+'.jpg")';
with Jquery
$(document).ready(function(){
var num = getRandomArbitrary(1,4);
$('#homepage').css("background-image",'../images/bg/' + num + '.jpg')
});
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
document.getElementById('homepage').style.backgroundImage = 'url(/whatever/img' + Math.floor( Math.random()*4 ) + '.png)';
First you need to get random number from 1 to 4.
I'll show you pure JavaScript and jQuery ways to do it:
JavaSript way:
//get random number from 1 to 4 and assign '.jpg' - or other format you need
var randomImage = "..\/images\/bg\/" + Math.floor((Math.random()*4)+1) + '.jpg';
//get body by ID
var homePageBody = document.getElementById('homepage');
//asign random image to body
homePageBody.style.backgroundImage=randomImage;
jQuery way:
$(document).ready(function () {
var randomImage = '../images/bg/' + randomFromTo(1, 4) + '.jpg';
//set background to body #homepage
$('#homepage').css("background-image", randomImage)
});
//define randomizer function
function randomFromTo(rfrom, rto) {
return Math.random() * (rfrom - rto) + rfrom;
}

Categories