Search code examples
jquerytoggleclass

Jquery Toggle to change image if .text() equal img[title]


With help from the community last week, I successfully implemented this code here

Now i need to do something similar but now compare html text with [title]. My code so far is below:

$(document).ready(function() {

 $(".views-field-field-success-stories-image-data .field-content").click(function() {
   var sharedata = $(this).text();
   $('#bannerContainer img[title = "'+sharedata+'" ]').addClass('selected');
 });
 $("#bannerContainer img").click(function() {
  if (
   $('#bannerContainer img').hasClass('selected', $('#bannerContainer img').removeClass('selected') ) );

 });
});


      <span class="field-content">The Grand Event Center</span>
      <span class="field-content">Choura Events Catering</span>
      <span class="field-content">El Dorado Park Golf Course</span>

<div id="bannerContainer">
 <img src="1.jpg" title="The Grand Event Center" class="selected">
 <img src="1.jpg" title="The Grand Event Center" class="selected"> 
 <img src="1.jpg" title="The Grand Event Center" class="selected">
</div>

<!--- My Goal
<div id="bannerContainer">
 <img src="1.jpg" title="The Grand Event Center" class="">
 <img src="1.jpg" title="The Grand Event Center" class=""> 
 <img src="1.jpg" title="The Grand Event Center" class="selected">
</div> ---->

I am having trouble wrapping my head around toggleClass for some reason.

Currently, if i click on any one of the spans, the 'selected' sticks and doesnt leave when i click on any another span.

What am I missing?

thanks in advance!


Solution

  • I usually accomplish this by just removing the class from all the related elements right before I add the class to the current element (the one you just selected).

    $(document).ready(function() {
     $(".views-field-field-success-stories-image-data .field-content").click(function() {
    
       // Add this next line
       $("#bannerContainer img").removeClass("selected");
    
       var sharedata = $(this).text();
       $('#bannerContainer img[title = "'+sharedata+'" ]').addClass('selected');
     });
     $("#bannerContainer img").click(function() {
      if (
       $('#bannerContainer img').hasClass('selected', $('#bannerContainer     img').removeClass('selected') ) );
     });
    });