javascript - How do I use an if statement to change the background image of a grandparent element using jQuery -


what trying use 3 clickable divs switches when clicked change background of element (using attribute data-image-src) grandparent of div.

heres html:

<header class="header-index locations-header col-lg-12 clearfix " data-parallax="scroll" data-image-src="images/2v1c8599.jpg">     <section class="locations-switcher col-md-12 clearfix">         <div class="first-switch col-sm-4"><h2>div one</h2></div>         <div class="second-switch col-sm-4"><h2>div two</h2></div>         <div class="third-switch col-sm-4"><h2>div three</h2></div>     </section> </header> 

and jquery:

$(".locations-switcher div").click( function() {         if($("div", this).attr('class') === "first-switch") {             $(".locations-header").attr( "data-image-src", "../images/img_4519_.jpg)" );         } else if( $("div", this).attr('class') === "second-switch") {             $(".locations-header").attr( "data-image-src", "../images/2v1c8599.jpg" );         } else if ($("div", this).attr('class') === "third-switch") {             $(".locations-header").attr( "data-image-src", "../images/ubc-interior.jpg" );         }     }); 

any clue why not working. i'm still new javascript , jquery. great.

use: if($(this).hasclass('first-switch')){ instead of:  if($("div", this).attr('class') === "first-switch") { 
  1. i think $('div', this) child divs, want @ element found.

  2. because there other classes on element, .attr('class') return whole string, .hasclass() check whole list

  3. you have parentheses in first source string

  4. depending on how data-image-src used might have trigger else redraw it. manually set .css('background-image', 'url(' + srcstring + ')')


Comments