Affan Ahmad
Affan Ahmad

Reputation: 451

How to check div background URL with JavaScript

I want to check div background URL with condition how to check if background URL equal this default.png than alert("please change image");.

Edit

<img style="background-image:url('default.png');">

Upvotes: 2

Views: 1754

Answers (4)

yashhy
yashhy

Reputation: 3086

To be more simple

HTML

<img src="default.png">

JS

if($('img').attr('src')=="default.png"){
    alert("please change image");
}

FIDDLE

--EDIT--

To answer your edited question

HTML

<img style="background-image:url('default.png');">

JS

var a = $('img').css('background-image');
var getIndex = a.indexOf('default.png')   //indexOf() is used, for checking the absolute image URLs
if(getIndex!=-1){
    alert("please change image");
}

Updated Fiddle

Upvotes: 1

Mihai
Mihai

Reputation: 659

var el = document.getElementById('my-image');

if(el.style.backgroundImage.indexOf('default') > 0) {
    alert("please change image");
}

pure JavaScript

Upvotes: 0

wrxsti
wrxsti

Reputation: 3504

if( $('img').css('background-image') == 'url(default.png)'){
    alert("Please change image.");
}

Hope this helps!

Upvotes: 4

Nitin Varpe
Nitin Varpe

Reputation: 10694

try

  var bg = $('#div').css('background-url');//div supposed to be id of div tag

if(bg==$('#img').attr('src'))//img supposed to be id of img tag
  .....
else
  ....

Upvotes: 0

Related Questions