0

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

Nocs
  • 71
  • 10
  • 2
    If you want to replace `$("#"+cw_id).crossword();` with `document.querySelector("#"+cw_id).crossword();`, you have to extend the `Element` or `HTMLElement` prototype instead of `Object`. Anyways, extending native prototypes is usually no longer a good solution, so I would prefer that you use a normal function: `crossword(document.querySelector("#"+cw_id));` PS: this is one of those JQuery thingies that screams for a rewrite, since rerendering a 2D array will be way easier and shorter than doing all those node manipulations. – Shilly Oct 30 '19 at 16:45
  • 2
    You would be better off not trying to make it follow jQuery's plugin pattern. – epascarello Oct 30 '19 at 16:59

1 Answers1

2

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 />
Namaskar
  • 2,114
  • 1
  • 15
  • 29
  • 2
    personally I would pass in the element reference and not worry about this to simplify it. `function crossword(element, options)` – epascarello Oct 30 '19 at 17:00
  • Thank you all for the suggestions and answers, i am on my way to make some tests since the best way is to avoid doing a direct convertion and go with the similar way which seems nice. – Nocs Oct 30 '19 at 17:10