4
I know it’s possible to use the on()
and delegate the selector, so it accesses the dynamic element from a static element, but if it cannot use the on()
, what to do?
For example, inside any function I need to take the id of an element added dynamically to change a style attribute and there is no event that fires the on()
:
jQuery
function(){
if(1 + 1 == 2){
//Não vejo como usar o on() nessa situação.
$("#elemento").css("color", "black");
}
//Talvez...
$("#elemento2").on((1 + 1 == 2), "#elemento", function(){
$("#elemento").css("color", "black");
});
}
Is there any other method, such as generating actions that are independent of other user actions or is it impossible to do this with jQuery?
I don’t understand! What do you want to do? You could explain briefly.
– Samir Braga
So you want a way for your script to always keep an eye out and be able to interact with new elements inserted in the DOM, without getting stuck to cursor events like Hover and click? I believe that a good are the Mutations Observers, but I still don’t have a very cool practice with them.
– Marcos Freitas
@Marcosfreitas, exact, I want to generate actions that are independent of the user, I will add this statement in the question, maybe I leave it more clarified.
– ptkato
Well, then I can only help you by indicating this article on M. Observers: http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers
– Marcos Freitas
Do you want something like an event that fires when a style is changed? Or do you just want to select the element with jQuery?
– bfavaretto
In this case, select the element with jQuery, in the example the
#elemento
should change the font color when 1 + 1 is equal to 2, but this does not happen, because the#elemento
is added dynamically.– ptkato
@Does Patrick have any specific case that raised that question? if yes please put the whole code or create a specific situation where this problem arises. To be honest I still don’t realize what you are looking to do...
– Sergio
By the way, take a look here, in case this is what you are looking for: https://github.com/naugtur/insertionQuery
– Sergio
I added another example to the code, I don’t know if it will help you understand...
– ptkato
If the action you want to be triggered is always the same, because you do not use CSS classes when creating dynamic elements?
– Kazzkiq
@Kazzkiq, something like
display: none
and thendisplay: block
?– ptkato
Patrick, what’s the problem with the code you posted (first if)? It works as long as the element exists on the page. And if it doesn’t exist, it makes no sense to change the color... Sorry, but it’s still hard to understand what you’re looking for.
– bfavaretto
Imagine that the element was added dynamically, without delegation it will not work.
– ptkato