Devtech Devtech - 1 year ago 81
CSS Question

How to change background image dynamically depending on the url

I'm trying to change dynamically on page load, the background depending on which URL you are. But it doesn't work for me.

var camera1 = "url1";
var camera2 = "url2";
var camera3 = "url3";
var currenturl = window.location;
if(camera1 == currenturl)
$(".breadcrumb-right").css("background", "url(url1.jpg) !important;");
else if (camera2 == currenturl)
$(".breadcrumb-right").css("background-image", "url(url2.jpg)");
else if (camera3 == currenturl)
$(".breadcrumb-right").css("background-image", "url(url3.jpg)");

Answer Source

Maybe you can improve your code doing something like this:

const cameras = ['url1', 'url2', 'url3'];
const currentUrl = window.location.href;
const el = $(".breadcrumb-right");

if (cameras.includes(currentUrl)) {
  el.css("background-image", `url(${currentUrl})`);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download