javascript - Jquery to change CSS background: Checking to see if div contains text, then action -


i trying css background based on weathertype.

if($('#weathertype:contains("cloudy")')) {     $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)'); } else if($('#weathertype:contains("clear sky")')) {     $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2rvko8k5ei/giphy.gif)') }; 

html

<body> <div class="text-center"> <h1> show local weather</h1> <h3>front end developer project</h3> <ul class="list-unstyled">   <i class="fa fa-home" aria-hidden="true"></i>   <li class="btn btn-default" id="city"></li>    <i class="wi wi-day-cloudy"></i>   <li class="btn btn-default" id="weathertype"></li> </br>   <i class="wi wi-thermometer"></i>   <li class="btn btn-default" id="ftemp"></li>    <i class="wi wi-strong-wind"></i>   <li class="btn btn-default" id="windspeed"></li> </ul> 

in code first if condition true since $(...) returns jquery object , truthy value first if block gets executed. use length property instead.

if($('#weathertype:contains("cloudy")').length) { //--------------------------------------^^^^^^-------     $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)'); } else if($('#weathertype:contains("clear sky")').length) { //------------------------------------------------^^^^^^-------     $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2rvko8k5ei/giphy.gif)') 

or can use jquery is() method returns boolean value.

if($('#weathertype').is(':contains("cloudy")')) { //------------------^^^^-------     $('body').css('background-image', 'url(https://hd.unsplash.com/photo-1430263326118-b75aa0da770b)'); } else if($('#weathertype').is(':contains("clear sky")')) { //-------------------------^^^^-------     $('body').css('background-image', 'url(https://media.giphy.com/media/3o7rc6sa2rvko8k5ei/giphy.gif)') 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -