Nocs
Nocs

Reputation: 71

How to convert a prototype jquery function to javascript prototype function

I am using a crossword in jquery and for some reason i need to convert it to javascript and avoid using jquery. I have managed to convert many parts of it but i have a big problem in a prototype function and i cant understand how to convert it.

Here is the code in summary :

$("#"+cw_id).crossword();

(function($) {
// plugin definition
$.fn.crossword = function(options) {
    .....
    // implementation code goes here.    
    return this.each(function(){
      ....
    }
})();
// end plugin definition

I have tried doing this and similar to this calls but nothing is working fine.

document.getElementById("#"+cw_id).crossword();
(function() {
// plugin definition
Object.prototype.crossword = function(options) {

})();
// end plugin definition

The actual code of this prototype function is at this link: https://github.com/electricg/jQuery-Html5-Crossword/blob/master/crossword.js#L1

and the caller is at the index link: https://github.com/electricg/jQuery-Html5-Crossword/blob/master/index.html#L62

I really need to know how to convert this prototype function back to javascript Thank you in advance for any help provided

Upvotes: 0

Views: 107

Answers (1)

Namaskar
Namaskar

Reputation: 2109

For similar functionality to jQuery, you're looking for HTMLElement.prototype.

HTMLElement.prototype.crossword = function(text) {
  this.innerHTML = text;
};

document.getElementById('crossword1').crossword('crossword here');
<div id=crossword1 />

Since that's a bad idea, I would use a function and bind the element to get a similar result. You can also pass it in as an argument, but that would require more refactoring of the existing code.

const crossword = function(text) {
  this.innerHTML = text;
};

crossword.bind(document.getElementById('crossword1'))('crossword here');
<div id=crossword1 />

Upvotes: 2

Related Questions