How to name and reuse a javascript function - javascript

I have the following bit of jQuery code that i want to reuse by calling it from other parts of my jQuery code. How would i do that?
$(document).ready(function() {
$('#share_mention').charcount({
maxLength: 140,
preventOverage: false
});
$('.countable').bind('update', function(evt, length, remaining) {
var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;
});
});

There are many ways to skin this cat but here is an approach.
var yourNameSpace = {};
yourNameSpace.YourFunction = function(){
$('#share_mention').charcount({
maxLength: 140,
preventOverage: false
});
$('.countable').bind('update', function(evt, length, remaining) {
var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;
});
}
$(document).ready(function() {
yourNameSpace.YourFunction()
});

First things first there is no such thing as a jQuery function. It's a javascript function.
The event is implicitly passed to the callback function.
function countCats (event) {}
$('.cats').on('click', countCats);

Related

How to make a loop with a Jquery subarray Json?

I have this array and I need to get the public_id and format values
{"resources":[{"public_id":"samples/3_zm3ex0","version":1643650862,"format":"jpg","width":4000,"height":3000,"type":"upload","created_at":"2022-01-31T17:41:02Z"},{"public_id":"mggvuz0xisg2nzkldbvx","version":1643520511,"format":"jpg","width":500,"height":549,"type":"upload","created_at":"2022-01-30T05:28:31Z"},{"public_id":"samples/cloudinary-group","version":1643517184,"format":"jpg","width":3000,"height":1526,"type":"upload","created_at":"2022-01-30T04:33:04Z"}],"updated_at":"2022-01-31T18:28:07Z"}
I try to do it like this but without success
$(document).ready(function() {
$("#fetch").click(function(event) {
$.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
$('#display').html('<p> Name: ' + emp.resources.public_id + '</p>');
$('#display').html('<p> Name: ' + emp.resources.format + '</p>');
});
});
});
I appreciate your help
The ressources attributes is an array so you have to loop each element in it. Your code should be like this :
$(document).ready(function() {
$("#fetch").click(function(event) {
$.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
//the attribute resource is an array so you have to loop each element in it
emp.resources.forEach(function(element){
var publicid = element.public_id;
var format = element.format;
$('#display').append('<div><p> Name: ' + publicid + '</p><p> Name: ' + format + '</p></div>');
});
});
});
});

.each loop only returning last result

My .each of alphabet is only returning the last result on "s" in:
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
relevant javascript code:
var suggestCallBack; // global var for autocomplete jsonp
var keywordCount = 0;
var alphabet = "abcdefghijklmnopqrstuvwxyz0123456789".split("");
$('body').on("click", '#submit', function() {
$('#keywords').html('');
var search_input = $("#keyword").val();
var language = $("#edit-domain").val();
callAPI(search_input, language);
_.each(alphabet, function(letter) {
callAPI(search_input + ' ' + letter);
callAPI(letter + ' ' + search_input);
});
return false;
});
function callAPI(s, language){
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?", {
"hl": language, // Language
//"ds":"yt", // Restrict lookup to youtube
"jsonp": "suggestCallBack", // jsonp callback function name
"q": s, // query term
"client": "youtube" // force youtube style response, i.e. jsonp
});
suggestCallBack = function(data) {
var suggestions = [];
var languageText = $("#edit-domain option:selected").text();
$('#keywordTable').show();
$.each(data[1], function(key, val) {
suggestions.push({
"value": val[0],
});
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
$('#keywordCount').text(++keywordCount);
$('#keywordtext').text(s);
$('#languageholder').text(languageText);
});
}
}
Here is a live preview: http://keyworda.com
The problem: (circled in red): http://i.imgur.com/gR46SuE.png
You are running into a problem with multiple simultaneous JSONP requests. Each of your callback function names must be different, or else they are overwriting each other and you'll only see the last request's result. You can read more about that here or here.
To fix your $.getJSON call you should remove the jsonp: 'suggestCallback' bit and give the callback function as the second parameter instead. The callback name is automatically filled by jQuery, because you put callback=? in the URL.
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?", {
"hl": language, // Language
"q": s, // query term
"client": "youtube" // force youtube style response, i.e. jsonp
}, function(data){
var suggestions = [];
var languageText = $("#edit-domain option:selected").text();
$('#keywordTable').show();
$.each(data[1], function(key, val) {
suggestions.push({
"value": val[0],
});
$('#keywordTable tr:last').after('<tr><td>' + s + '</td><td>' + val[0] + '</td><td>0</td><td>0</td><td>0</td></tr>');
});
});
Here's some working code: http://plnkr.co/edit/O2JKhhOziRczIMkctQc7?p=preview

How to set an element property from within a callback function

I have this "service" element where I would like to set the property "bookmarks" with the function getTree, which takes a callback function.
My problem is that I don't see how I could reach the property from within the callback function where "this" is undefined!!
<dom-module id="...">
<style>
:host {
display: none;
}
</style>
<script>
Polymer({
is: "bookmark-service",
properties: {
bookmarks: {
type: Array,
value: function() { return [{title:"init"}]; }
}
},
created: function() {
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
} );
console.log(this.localName + '#' + this.id + ' was created');
console.log("Bookmark: " + this.bookmarks[0].title + '.');
},
...
You could save a reference for this before calling getTree:
var that = this;
chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
that.bookmarks = bookmarkTreeNodes;
console.log(that.localName + '#' + that.id + ' in getTree.');
});
You can use bind to set this in your callback function.
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
this.bookmarks = bookmarkTreeNodes;
console.log(this.localName + '#' + this.id + ' in getTree.');
}.bind(this) );
That was a part of my problem and I prefer not to use "bind" which I fear may have side effects with this and looks more complicated.
But another problem, was the asynchronous nature of getTree. For this, I had to add an observer.
Also, the properties doesn't even exist in "created" phase, I had to use "ready"
So here is the almost final result:
properties: {
bookmarks: {
type: Array,
value: function() { return [{title:"init"}]; },
observer: 'bookready'
}
},
bookready: function(){
console.log("Bookmark ready: " + this.bookmarks[0].title + '.');
},
ready: function() {
var self = this;
chrome.bookmarks.getTree(
function(bookmarkTreeNodes) {
self.bookmarks = bookmarkTreeNodes[0].children;
}
);
console.log(this.localName + '#' + this.id + ' was readied');
console.log("Bookmark: " + this.bookmarks[0].title + '.');
},

Javascript Parameters Function on Many Events

I'm trying to implement hammer.js to swipe pages (like a book) and I did it. The problem is that this works
var idHammer1 = document.getElementById("pageHoja1")
//var hammertime = new Hammer(myElement, hammerOptionsPan);
var objHammer1 = new Hammer(idHammer1);
objHammer1.on('panleft panright', function(ev)
{
//DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
if (ev.type==='panleft')
{
if (!(gSceneActual===2))
{
gSceneActual = 2;
$(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
}
}
else if (ev.type==='panright')
{
}
});
but this doesn't:
var fSwipe1 = function(ev)
{
//DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
if (ev.type==='panleft')
{
if (!(gSceneActual===2))
{
gSceneActual = 2;
$(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
}
}
else if (ev.type==='panright')
{
}
}
var idHammer1 = document.getElementById("pageHoja1")
//var hammertime = new Hammer(myElement, hammerOptionsPan);
var objHammer1 = new Hammer(idHammer1);
objHammer1.on('panleft panright', fSwipe1(ev))
and this also don't work
function fSwipe1(ev)
{
//DBLog("obj1 - gSceneActual Antes: " + gSceneActual + " // X: " + ev.center.x + " Y: " + ev.center.y);
if (ev.type==='panleft')
{
if (!(gSceneActual===2))
{
gSceneActual = 2;
$(":mobile-pagecontainer").pagecontainer("change", "#pageHoja2", { transition: "slide", reverse: false});
}
}
else if (ev.type==='panright')
{
}
}
and since I need to add this event to many pages (variable #) I cant hardcode it... How can I make it variable inside a cycle?
Thanks!
Ah, without knowing the extent of the errors, I do see:
objHammer1.on('panleft panright', fSwipe1(ev));
Here, you are rendering the function automatically, but what you actually want is to use a closure so that the function does not get rendered until the event gets hit. I'm not sure what ev represents, but if it is the event object, then this should work:
objHammer1.on('panleft panright', fSwipe1);
Where all you are doing is passing in the function that you want to be the callback and the even will automatically call this function and pass the event object as the first parameter.
A few other things that I notice:
make sure that you include the javascript library for Hammer
Make sure that gSceneActual is defined before it is evaluated at gSceneActual===2
Make sure that jQuery library is included

Another jQuery autocomplete issue

So, i have read at least 20-30 auto complete problems here on so and i cannot find any solutions. For some odd reason i keep getting value = undefined. Here is my code.
//Cycles through each input and turns it into a person searcher.
$.each(settings.input, function() {
var input = $(this);
input.autocomplete({
delay: 70,
minLength: 2,
source: function(req, add) {
var val = input.val();
$.post(VUI.SITE_URL + "scripts/autocomplete/_AutoComplete.php", {q: val, display_count: settings.displayCount, action: "user"}, function(data) {
data = eval("(" + data + ")");
if (data.length > 0) {
var results = new Array(data.length);
$.each(data, function(key, value) {
results[key] = {desc: value, value: value.firstname + " " + value.lastname};
});
add(results);
} else {
add(["No results..."]);
}
});
},
select: function(event, ui) {
alert(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
}
}) // end auto complete.
.data("autocomplete")._renderItem = function($ul, item) {
var $li = $("<li></li>"),
$inner = $("<div class='st-display side-content clearfix'style='padding-top:6px'></div>"),
$a = $("<a></a>"),
$img = $("<div class='image fl'></div>").html(ST.Image.getImage({
uid: item.desc.uid,
type: ST.ST_IMAGE_TYPE_THUMBNAIL_SMALL
})),
$content = $("<div class='content fl'></div>").html(
item.desc.firstname + " " + item.desc.lastname + "<br/>" +
"<span class='color:#979797;font-weight:bold'>" + item.desc.city + ", " + item.desc.state + "</span>"
);
$inner.append($img).append($content);
$a.append($inner);
$li.append($a);
$ul.append($li);
return $ul;
} // end _renderItem */
I tried to make it so that its very straight forward. But it wont work! (its facebook like auto complete). The auto complete displays properly (item does not equal undefined at that point), but when i highlight it, item becomes undefined so item.value (line 6347 of jquery.ui.1.8.13) throws exception!
Anyone see problems?
Here is something interesting... When i do not use data("autocomplete")._renderItem (for custom completion) the selecting works! ... So why does overriding the custom rendering cause issues? I am even returning the UL.
The only thing in your code that's different from a working version I've got of something very similar is that I initialise $li with:
var $li = $( '<li></li>' ).data('item.autocomplete', item);
That attaches the data to the list item which I think the autocomplete plugin uses to get the value at selection time.
Hope it helps

Categories