Add class Dynamically

Asked

Viewed 346 times

5

I own a Carousel where the buttons prev and next 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 as div has not yet been generated.

Using the function on didn’t work either:

$("#owl-main-banner").on("load", function(){
    $(".owl-prev").addClass("theme-color");
});
  • Does the plugin not have a callback when deploy is done? What is the plugin?

2 answers

1

For the class used in your code snippet, I suppose you are using the Owl Carousel plugin, I also use it. What you are trying to do can easily be reached the callback afterInit of the plugin itself.

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

I’ll leave the solution here, but I’ve prepared one 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 achieve the expected result, good luck!

1

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

Example:

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

Where fn’s are functions.

These shall be executed in addition order.

Note:

If the .done() not working, try to $.when().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.