Getting jQuery to work in Jetpack - javascript

I am experimenting with Jetpack and I would like to parse all the years in a given html page and then wrap the year with a link to the Wiki page. I tried the code in jquery and there it works but now I am using it in Jetpack and it gives an error $(doc).replace is not a function. I am definitely new to Jquery / Jetpack so maybe I am missing something really easy but your help is much appreciated.
EDIT: I have tried the suggestions but I am still stuck. The weird thing is that this
JQuery function works:
(function($) {
$.fn.clickUrl = function() {
var regexp = /([1-2][0-9][0-9][0-9])/gi;
this.each(function() {
$(this).html(
$(this).html().replace(regexp,'<ahref=\"http://nl.wikipedia.org/wiki/$1\">$1<\/a>')
);
});
return $(this);
}
})(jQuery);
and basically, I would like to 'port' this function to Jetpack.
This is the 'old' non-working port of my JQuery function to Jetpack:
jetpack.statusBar.append({
html: "Hyperlink Years",
width: 80,
onReady: function(widget){
$(widget).click(function(){
var regexp = /([1-2][0-9][0-9][0-9])/gi;
var doc = jetpack.tabs.focused.contentDocument;
$(doc).each(function() {
$(this).html(
$(doc).replace(regexp,'<a href=\"http://nl.wikipedia.org/wiki/$1\">$1<\/a>'));
});
return $(doc);
});
}
});

I'm not familiar with jetpack, but your jquery seems to be quite messed up.
If "doc" is an HTML document, then doing $(doc).each() doesn't really make sense. It would only loop once, and "this" would be the same as doc.
Then later you are doing $(doc).replace(regexp, ...), but replace() is not a jquery function. You might have wanted to do .html().replace(regexp, ...); HOWEVER, I do not recommend doing this because it will not work - you will just end up replacing any numbers in the document, even if they are part of another URL or the HTML of the page.
For more information, refer to this question or google for jquery text nodes:
Find text string using jQuery?

Related

Node js, Dollar Sign, html, express

I just started using Node.js and learning web development but I'm a bit unclear on the meaning/function of some symbols/signs.
For example, in the following code:
$(function() {
$.getJSON('/data', function(data) {
var $dataContainer = $('#data-container');
if (data.error) {
$dataContainer.html('Error! ' + data.error);
return;
}
// Clear the loading message.
$dataContainer.html('');
data.records.forEach(function(record) {
var $galleryCard = $('<div class="gallery-card" />');
if (record.picture[0]) {
// Just show the first picture, if it has one.
$('<img />').attr('src', record.picture[0].url).appendTo($galleryCard);
}
var $label = $('<strong />').text(record.name);
$galleryCard.append($label);
$dataContainer.append($galleryCard);
});
});
});
Why is there a "$" before the function()? What about when the $ is in front of ".getJSON", in front of the variable DataContainer, and infront of ('#data-container')? Also, what does the # infront of data-container mean?
Thank you!
It looks like the code you're referring to is using jQuery: a JavaScript library that makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler.
The $ is, simply put, the shortcut to access the jQuery library. Syntax would be $(selector).action().
The # symbol you're referring to is a selector, particularly referring to id. Selectors allow you to select and manipulate different elements, in this case an element (possibly a div) with an id="data-container".
If you would like to read more about jQuery their website is: https://jquery.com/
To learn more about selectors, go here: https://api.jquery.com/category/selectors/
what $ in your code means is alias of jQuery (which is a javascript library) object. (see this).
In simpler words basically, your code has nothing to do with nodejs(server side javascript) but it is related to browser supported version of javascript.

Custom Unobtrusive Validation Method Not Firing as Per Documentation

I've been attempting to implement a ASP.NET MVC custom validation method. Tutorials I've used such as codeproject explain that you add data-val-customname to the element. Then jQuery.validate.unobtrusive.js then uses the third segment of the attribute
data-val-<customname>
as the name of the rule, as shown below.
$.validator.addMethod('customname', function(value, element, param) {
//... return true or false
});
However I just can't get the customname method to fire. By playing around I have been able to get the below code to work, but according to all the sources I've read Unobtrusive validation should not work like this.
$.validator.addMethod('data-val-customname', function(value, element, param) {
//... return true or false
});
I've posted an example of both methods
jsfiddle example
Any help would be much appreciated
I've updated my question hopefully to make clearer.
I have finally found got there in the end, but still feels like too much hard work and therefore I've probably got something wrong. Initial I was scuppered by a bug in Chrome Canary 62 which refused to allow the adding of a custom method.
My next issue was having to load jQuery, jQuery.validate and jQuery.validate.unobtrusive in the markup and then isolate javascript implementation in a ES6 class. I didn't want to add my adaptors before $().ready() because of my class structure and loading of the app file independent of jQuery. So I had to force $.validator.unobtrusive.parse(document);.
Despite this I was still having issues and finally debugged the source code and found that an existing validator information that is attached to the form was not merging with the updated parsed rules, and essentially ignoring any new adaptors added.
My final work around and admit feels like I've done too much, was to destroy the initial validation information before my forced re-parse.
Here is the working jsfiddle demo
Here is some simplified code
onJQueryReady() {
let formValidator = $.data(document.querySelector('form'), "validator" );
formValidator.destroy();
$.validator.unobtrusive.adapters.add("telephone", [], function (options) {
options.rules['telephone'] = {};
options.messages['telephone'] = options.message;
});
$.validator.unobtrusive.parse(document);
$.validator.addMethod("telephone", this.handleValidateTelephoneNumber);
}

Is Using Javascript inside a jQuery function is a bad practice?

I know basics of both jQuery and JavaScript.I would like to follow a good coding practice. Is using JavaScript inside a jQuery function is a bad practice?
For exapmle:
$(document).ready( function() {
$('#dqualification').change(function() {
document.getElementById("demo").innerHTML = "Resolve following errors";
});
});
Nope, its fine, and it's done all the time.
Consider:
$("#myDiv").on("click", function(){
var a = this;
});
The line var a = this; is pure JavaScript. There is no "jQuery Version" of var a = this;.
jQuery provides convenient ways of doing things in JavaScript that might be difficult to write and code yourself in pure JavaScript. It doesn't replace JavaScript, it just 'adds to it'.
Remember, jQuery is just a JavaScript library. So everything ends up as JavaScript at the end of the day.
It is not directly bad practice, it is more a bit inconsistend. Both is javascript. But why would you do things like in your example? If you have jQuery available, you could use it!
$(function() {
$('#dqualification').change(function() {
$("#demo").html("Resolve following errors");
});
});

trying to map someFunction.jQuery to "$"

I found a function (via this person's github) that I might use in my script that mimics the functionality of an API object.
Here's the relevant code from the link:
unsafeWindow = (function() {
var e1 = document.createElement('p')
e1.setAttribute('onclick', 'return window;');
return e1.onclick();
})();
Where the poster says you can use the function in the format unsafeWindow.jQuery
Now, I want to be able to use $ instead of the jQuery keyword elsewhere in my code. I tried learning from this stack overflow question to simplify it and re-wrote the code like so:
(function($){
var e1 = document.createElement('p')
e1.setAttribute('onclick', 'return window;');
return e1.onclick();
})(jQuery);
But it didn't work. I guess I could just try something like $ = unsafeWindow.jQuery in order to map to the $, but I wanted to try to do it in the format seen above.
You would map $ to unsafeWindow.jQuery like so:
unsafeWindow = ( function () {
var dummyElem = document.createElement('p');
dummyElem.setAttribute ('onclick', 'return window;');
return dummyElem.onclick ();
} ) ();
var $ = unsafeWindow.jQuery;
// Now you can use the page's jQuery. EG:
$("body").append ('<p>Content added by unsafeWindow.jQuery</p>');
But keep in mind:
This is a Hack, and it will probably stop working around Chrome version 28.
It may still fail due to a race condition about when userscripts fire. To fix that, add // #run-at document-end to the userscript's metadata block.
Don't do things this way! It will only cause grief, side effects and maintenance headaches.
For userscripts: use this technique (best cross-browser)  or  this technique (relies on page's jQuery, but the example shows how to use GM_ functions too).
For full extensions or content scripts:, use this technique (use the manifest.json and keep everything properly sandboxed).

Add function to existing JQuery plugin

Is it possible to add a function to a plugin without modifying the actual plugin? Can I do something like this in my site's js file?
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
}
or
(function($){
$.fn.Watermark.Refresh = function() {
$.Watermark.HideAll();
$.Watermark.ShowAll();
};
})(jQuery);
neither worked, the first says $ is undefined, the second that jQuery is undefined...
ideas?
Solution: Either method works, just include the jquery file before the site js file.
You can add those functions if you want to, but you'll have to make sure that you're also loading jQuery itself and the plugin to be modified. If you're getting those errors (that jQuery or "$" are not defined), then you have not correctly done that.
Now, though it's true that you can add those functions, I have to wonder what the point would be. If I were to do this, for example:
$.fn.css.myFunction = function() { return "hello world"; };
then it would be possible to call it:
var str = $.fn.css.myFunction();
but so what? What good does that do me? I don't think it's very useful.
Make sure you are including the plugin after jQuery.

Categories

Resources