technopeasant
technopeasant

Reputation: 7939

Run JavaScript function on element defined with jQuery

Not sure I titled this well.. show's that I'm in unfamiliar territory. How can I run a JavaScript function based off of the element called in a jQuery function?

Theory:

<script type="text/javascript">
  $.fillit('video');
</script>

(run fillit on video tag present in page.. interchangable with other elements)

$.fillit = function(){
  this is where it says "run on the tag defined in the jQuery function"
}):

Upvotes: 0

Views: 918

Answers (4)

technopeasant
technopeasant

Reputation: 7939

Someone answered with a link to this: http://docs.jquery.com/Plugins/Authoring

exactly what I was looking for. claim your kudos!

(function( $ ){

  $.fn.fillit = function() {

    this.fadeIn('normal', function(){

      var container = $("<div />").attr("id", "filled")
        .appendTo(container);

    });

  };
})( jQuery );

Upvotes: 0

Alex
Alex

Reputation: 35409

$.fn.extend({
    fillit : function(){...}
});

then...

$('.video').fillit();

Edit (after comments)

To fill a dom element with other elements/html:

var img = document.createElement('img');
img.setAttribute('src', 'somesrc.jpg');

$('.video').append(img);

or

$('.video').html('<img src="somesrc.jpg"/>');

Upvotes: 1

Nathan Bell
Nathan Bell

Reputation: 2362

technopeasant, it sounds like you are using a jquery plugin (in your example, a plugin called 'fillit') and it is asking you to run the plugin on a tag or series of tags. Sorry if I misunderstood your question.

If that is the case, all you need to do is one of two things. If you are trying to run it on a very specific element in the HTML page (one with an id like <div id="myvideo"></div>) then all you need to do is run:

$('#myvideo').fillit();
//Notice the '#' symbol, that looks up the element with an id of 'myvideo'

If you want to run the plugin on a series of elements (like all <p> tags in the entire document, you'd run something like:

$('p').fillit()
//notice no '#', it's just looking up all <p> tags regardless of ID.

Take a look at the jQuery documentation regarding selectors to get a more concrete idea of how these selectors work:

http://docs.jquery.com/How_jQuery_Works

Upvotes: 0

Ben
Ben

Reputation: 1535

You can do it the way you described like so

<script type="text/javascript" language="javascript">
$.fillit = function(content)
{
$("result").html(content);

}

//call function
$.fillit("HELLO WORLD");

</script>

or as Alexander just posted if you want to do it on the selected element.

I don't think adding functions directly to jquery with $.func = is a good idea though. If jQuery ever adds a fillit method your method will conflict with theirs.

Upvotes: 0

Related Questions