Unexpected jQuery syntax error by chaining a plug-in after .find() - javascript

I've baked a plug-in to handle runtime searches on input fields I'm using all over a big site.The plug-in works perfect in every situation but this http://jsfiddle.net/tonino/v8d2A/
$(document).ready(function () {
var callback_methods = { /* methods here */ };
var input_html = '<div class="search"><input name="search-field" value="Search..."></div>';
$(document).on('click', 'div.add', function (event) {
if (!$('li div.add + div').hasClass('search')) {
var input = $(this).after(input_html).parent().find('input');
input.focus();
input.hunter({url:'<?php echo $this->request->base; ?>/searches', callback:callback_methods, var_name:'data[Search][term]'});
// other code after
}
});
});​
If I comment the hunter plug-in everything works fine.
I'm sure is some concept on how it must be structured, here is the code: jquery.hunter.1.3.js
Why my plug-in make this error in this situation, where I'm wrong on writing it?

the problem is this part of your code:
var selector = this.selector;
var def_css = {backgroundPosition:'-16px center', paddingLeft:$(selector).css('padding-left')}
if (settings.loader) { setStyle(def_css); }
var selector = this.selector;
and later:
$(this.selector).blur(function () {
first of all your code wont work when the if-condition is fulfilled, because you are trying to redeclare the variable 'selector' inside the if block. just leave the var-statement out there:
if (settings.loader) { setStyle(def_css); }
selector = this.selector;
but YOUR MAIN-problem is that 'this.selector' contains '.parent() input' which i doubt is a valid jQuery selector.
why are you doing that? why dont you just use $(this) save it into a variable and use this???
eg:
// first line in your plugin
$this = $(this)
// later you could use the $this var
$this.blur(function () {

To get rid of the error change this line:
var input = $(this).after(input_html).parent().find('input');
To the following:
var input = $(input_html).insertAfter($(this));
The core problem though is that the jquery.hunter plugin is using the this.selector variable for some reason - you don't need this - the plugin should use $(this) instead of $(this.selector)

Related

Why is this jQuery submit event not triggering correctly?

I am trying to create a function that takes a user's input and uses it to search Wikipedia. Then, at least for now, show the first result by appending it to the element call "#list".
I have tested the API, the JSON syntax, the appendTo syntax all independently and confirmed that they are working fine. But the event does not execute.
$('form').submit(function(event)
{
var $input = $(event.target).find('input');
var search = $input.val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&titles=Main+Page&srsearch="+search+"&srprop=wordcount%7Ctimestamp%7Csnippet%7Ctitlesnippet",
function(data)
{
var item = data.query.pages.search[0].titlesnippet;
var itemDesc = data.query.pages.search[0].snippet;
var html = $('<li>').html(item+"<br/>"+itemDesc);
html.prependTo('#list');
});
});

How can I retrieve the target element that a jquery plugin is attached to?

I am new to writing JQuery Plugins...and have a question regarding returning the selector used to bind the plugin to.
Lets say we attach a jQuery plugin to an element like this...
$(".someClass").viEdit();
And this is the Plugin ...
(function ($) {
$.fn.viEdit = function () {
var myTarget = "????"; // See Below
};
}(jQuery));
Now...How can I retrieve the target that was used to bind the jQuery?
I don't mean $(this), I'm looking for .someClass in this case.
As a second example, if it was set like this...
$("#myElement").viEdit();
I would be looking for...
#myElement
Any help would be greatly appreciated!
You can use this.selector:
http://jsfiddle.net/3NAwD/
(function ($) {
$.fn.viEdit = function () {
console.log(this.selector);
};
}(jQuery));
Note that something like $(document.getElementById('someId')).viEdit(); will give you a blank selector.
There were a .selector property, which is deprecated in newer versions.
The advised method now is to pass it as a option like
(function ($) {
$.fn.viEdit = function (options) {
var myTarget = options.target;
};
}(jQuery));
$("#myElement").viEdit({
target: '#myElement'
});

jQuery .attr code to work in Drupal

Check out my jsFiddle: http://jsfiddle.net/KevinOrin/zuFae/
The code successfully works there but not on the Drupal site I am coding it for: http://gossiptalk.info/users/gossiptalk
I copied out the html directly from the Drupal DOM output and no matter where I put the js it doesn't work. And yes it's loading the jQuery library. Any thoughts?
$(document).on("click", function () {
var _href = $("#map-addr").attr("href");
var _addr = $("#map-addr div.field-item").text();
$("#map-addr").attr("href", _href + _addr);
});
I believe drupal uses jQuery.noConflict therefore the $ will no longer reference the jQuery object. Just use jQuery instead of $.
jQuery(document).on("click", function () {
var _href = jQuery("#map-addr").attr("href");
var _addr = jQuery("#map-addr div.field-item").text();
jQuery("#map-addr").attr("href", _href + _addr);
});
You can also just use the 'jQuery' variable instead of the $ variable in your code.
See: http://drupal.org/node/171213
http://drupal.org/update/modules/6/7#javascript_compatibility
var jq = jQuery.noConflict();
jq(document).on("click", function () {
var _href = jq("#map-addr").attr("href");
var _addr = jq("#map-addr div.field-item").text();
jq("#map-addr").attr("href", _href + _addr);
});
You should be able to use this and still write jQuery like you're used to inside it, since it makes the $ local to itself and outputs to jQuery. It generally works the same as document.ready
(function($){
$(document).on("click", function () {
var _href = $("#map-addr").attr("href");
var _addr = $("#map-addr div.field-item").text();
$("#map-addr").attr("href", _href + _addr);
});
})(jQuery);

Refer to immediate selector object with jQuery?

I'm trying to learn some jQuery, and I setup a test page with the following code:
<a id='encode' href='javascript: void(0)'>encode</a> |
<a id='decode' href='javascript: void(0)'>decode</a> |
<br/>
<textarea id='randomString' cols='100' rows='5'></textarea>
<script type='text/javascript'>
$(document.ready(function () {
$('#encode').click(function() {
$('#randomString').val(escape($('#randomString').val()));
});
$('#decode').click(function() {
$('#randomString').val(unescape($('#randomString').val()));
});
});
</script>
The idea is I can put something in the textarea and click either "encode" or "decode", and it will either escape or unescape what I put into the textarea.
This code works just fine, but my question has to do with how I am changing the value of the textarea. In my code, I am selecting the textarea value twice: once to (un)escape it, and once again to change the value. IMO this seems clunky and maybe unnecessary. I thought maybe I could do something like this instead:
$('#randomString').val(escape(this));
But this seems to refer to the object of the link I clicked, not the #randomString selector, so is there some other magic word I can use to reference that $('#randomString')?
$('#randomString').val(escape(this));
This does not get the object you want. It is effectively the equivalent of doing this:
var foo = escape(this);
$('#randomString').val(foo);
this only means something different when you start a new scope with a function definition.
jQuery does offer this kind of functionality with a callback option:
$('#randomString').val(function (idx, oldVal) {
return escape(oldVal);
});
The second parameter is the current value of the element; the return value sets a new value for the element.
You can try this
$(document.ready(function () {
$('#encode').click(function() {
var $randomString = $('#randomString');
$randomString.val(escape($randomString.val()));
});
$('#decode').click(function() {
var $randomString = $('#randomString');
$randomString.val(unescape($randomString.val()));
});
});
The short answer, if I understand you correctly, is no. There isn't a way to refer to $('#randomString') where you're talking about. It's just a parameter to the val method, so it's just plain JavaScript syntax, no jQuery "magic".
To accomplish the task at hand and make the code cleaner and less clunky, I would save off the jQuery object for #randomString so you don't have to keep creating it:
$(document.ready(function () {
var $rndStr = $('#randomString');
$('#encode').click(function() {
$rndStr.val(escape($rndStr.val()));
});
$('#decode').click(function() {
$('#rndStr').val(unescape($rndStr.val()));
});
});
You could make it a little generic:
$.fn.applyVal = function(func) {
return this.each(function() {
$(this).val( func( $(this).val() ) );
});
};
Then the following call is enough:
$('#randomString').applyVal(escape);

Question about cache in javascript/jquery

I wonder if selector "$cacheA" will be cached on page load in the example below?
// MY JQUERY FUNCTION/PLUGIN
(function( $ ){
$.fn.myFunction = function() {
var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
$cacheD.click(function(){
$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();
});
};
})( jQuery );
// END JQUERY FUNCTION/PLUGIN
$(window).load(function(){
$('#mySelector').myFunction();
});
Would it be any reason to do this:
$(window).load(function(){
var $mySelector = $('#mySelector');
$mySelector.myFunction();
});
If, inside your "load" handler, you were to do many jQuery operations with "$mySelector", then saving that in a variable would be a good idea. However, in your example, you only use the value once, so it really makes no difference at all.
Firstable, $cacheA and others inside click function will be undefined.
$cacheD.click(function(){
$cacheA.toggle();
$cacheB.fadeIn();
$cacheC.slideUp();
});
Second,
$.fn.myFunction = function() {
var $cacheA = this,
$cacheB = $cacheA.children(),
$cacheC = $cacheB.eq(0);
$cacheD = $cacheA.parent();
}
So, after $('selector').myFunction() how can I use $cacheB, $cacheC and $cacheD? Where they are will store?

Categories

Resources