Add class dynamically

5

I have a carousel where the prev and next buttons are generated by the plugin.

The problem is even trying to add a class with the traditional method $(".owl-prev").addClass("theme-color"); the same does not apply because div has not yet been generated.

Using the on function also did not work:

$("#owl-main-banner").on("load", function(){
    $(".owl-prev").addClass("theme-color");
});
    
asked by anonymous 28.04.2015 / 18:00

2 answers

1

You can use the $.done method of jQuery . When the plugin is generated yes you call your addClass() .

Example:

var dfd = $.Deferred();
dfd.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )

Where fn's are functions.

These will be executed in order of addition.

Note:

If .done() does not work, try $ .when () .

    
29.04.2015 / 15:06
1

For the class used in your code snippet, I assume you're using the Owl Carousel plugin, I also use it. What you're trying to do can easily be reached with the% co call of the plugin itself.

You'll want to take a look at the documentation for the Owl Carousel especially in section 2 - Callbacks

I'll leave the solution here, but I've prepared a demo for you to see the result.

CSS

/* Custom class for the nav - Classe customizada para navegação */
.theme-color {
  color: #fff;
  background: #3ABC4B !important;
  opacity: 1 !important;
}

JS

$(document).ready(function () {

// Inicializa o plugin e define algumas variáveis de customização
$(".owl-carousel").owlCarousel({
  navigation: true,
  navigationText : false,
  navigationText : ["<",">"], 
  pagination:  false, // Esconde a navegação com "dots"
  afterInit : attachEvent // Após a inicialização, inclui um novo evento
});
// Com essa função abaixo encontramos o elemento pela classe e adicionamos
// a classe customizada, poderia ser qualquer outra função que você
// decidisse criar, bastaria chamar essa função na variável 
// 'afterInit :' quando fosse inicializar o plugin
function attachEvent(elem){
 elem.parent().find('.owl-prev').addClass('theme-color')
 };

});

demo

I hope you can achieve the expected result, good luck!

    
20.05.2015 / 21:00