user3699998 user3699998 - 4 months ago 36
Javascript Question

Bootstrap carousel should Fire event on load and slide

I have a function that checks the colour of the image, if dark/light adds a class to the header.


  • I want to have this function running inside
    myCaruosel
    Bootstrap.

  • The
    getImageBrightness
    should be fired for each image.



I can't get it working inside the carousel function.

Any help much appreciated.

http://jsfiddle.net/s7Wx2/115/

Answer

use find event to get active image src instead of using this.src :

 /// debug code

$(document).ready(function() { var imgs = document.body.getElementsByTagName('img');

///Load  getImageBrightness function

$("img").on("load", function() {

  getImageBrightness(this.src, function(brightness) {
    if (brightness < 256 / 2) {
      $('header').addClass('dark');
    } else {
      $('header').addClass('light');
    }
  });

}).each(function() {
  if (this.complete) $(this).load();
});

var img_src = $('#MyCarousel').find('.carousel-item.active img').attr('src');
     getImageBrightness(img_src, function(brightness) {
     console.log(brightness);
    if (brightness < parseInt(256 / 2)) {
      $('header').toggleClass('dark');
    } else {
      $('header').toggleClass('light');
    }
  });
///Load carousel and trigger the getImageBrightness Function here
 $('#MyCarousel').on('slide.bs.carousel', function () {
var img_src = $('#MyCarousel').find('.carousel-item.active img').attr('src');
     getImageBrightness(img_src, function(brightness) {
     console.log(brightness);
    if (brightness < parseInt(256 / 2)) {
        $('header').removeClass('light');
      $('header').addClass('dark');
    } else {
        $('header').removeClass('dark');
      $('header').addClass('light');
    }
  });
 }).each(function() {
  if (this.complete) $(this).load();
});

});

Fiddle

Comments