tags:

views:

67

answers:

5

Hi, I searched for a solution like:

if( content from $('#div') is change -> start function test(); )

I change the content with $('#div').html('blub');

Thanks in advance! Peter

PS: I know, it is possible with setTimeout, but this is a really dirty solution :/

A: 

Just out of curiosity, if you are changing the div content with your code, couldn't you just call test() when you change the div?

$().event(function(){
    $('#div').html('blub');
    test();  //call your test function
});
Chris
+2  A: 

I think the best way to achieve that is to write a custom html function, something like this:

function changeHtml(content) {
    this.html(content);
    yourChangeHandler(this);
}

Edit: Or with a change event... http://forum.jquery.com/topic/what-is-the-best-way-to-handle-onchange-event-on-a-div

Tarentrulle
Thats it! Thank you very much!
Peter
`$(this)` or `this` not `$this`
Peter Ajtai
@peter, thank you, edited :)
Tarentrulle
+1  A: 

Hi, It can be done 2 ways 1) create new jquery method and call your test function before calling jquery hml function. So instead of $('#div').html('blub') you will write $.myhtml($("#div").html()). Code below might give you some idea(Got it working)

**jQuery.extend(jQuery, { myhtml: function (arg1, html) { 
         test();
       return arg1.html(html); 
} });** 
 call by $.myhtml($("#div"), $("#div").html()) or $.myhtml($("#div"))

2) override jquery html function http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm

var refhtml = $.fn.html;

$.fn.html = function() {
    $(this).each(function() {
       test();
        refhtml .apply(this, arguments);
    });
};
Ayaz Alavi
Nice! I really like your #2 solution. I've never heard about jQuery function overriding before :)
Tarentrulle
see this http://www.bennadel.com/blog/1624-Ask-Ben-Overriding-Core-jQuery-Methods.htm . it requires a bit of testing though but it is feasible solution in such scenarios
Ayaz Alavi
A: 

Just chain .test() on after .html.

$('#div').html('blub').test();

To achieve this, simply make a little plugin.

Like this (jsFiddle example):

jQuery.fn.test = function() { 
    // Your test function goes here. 
    return this.each()};

That return is needed, since a method must return the jQuery object, unless explicity noted otherwise for a jQuery plugin. Read about jQuery plugins here.

Peter Ajtai
Please explain the down vote.
Peter Ajtai
A: 

This will do the job $('#div').change(function(){ test(); });

Avinasha