-2

I have the condition:

console.log(jQuery(".sl-slide:visible .bg-img").css("background-image"));

if(jQuery(".sl-slide:visible .bg-img").css("background-image") == "url(http://pacificolife.com/wp-content/uploads/2016/08/bw1-1.jpg)")
{
    console.log("Here");
}

but when the background is equal to that url, nothing happens. What am I doing wrong?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

1

That's because those are not the same strings:

var background = jQuery(".sl-slide:visible .bg-img").css("background-image"))

If you do that, background will have the value of url("http://pacificolife.com/wp-content/uploads/2016/08/bw1-1.jpg")

No matter if on your css file, you write:

.sl-slide:visible .bg-img {
  /* with '' */
  background-image: url("http://pacificolife.com/wp-content/uploads/2016/08/bw1-1.jpg");
  /* without '' */
  background-image: url(http://pacificolife.com/wp-content/uploads/2016/08/bw1-1.jpg);
}

The output will always be the same.

Solutions:

  1. Do the comparsion with the exact same string.
  2. Remove the URL(). Based on this answer:

Code:

var bg = jQuery(".sl-slide:visible .bg-img").css("background-image")); 
var url = bg.replace(/(?:^url\(["']?|["']?\)$)/g, "");
console.log(url === 'http://pacificolife.com/wp-content/uploads/2016/08/bw1-1.jpg');
// true

Check this fiddle

finw3
  • 453
  • 5
  • 10