I'm not sure if the question were asked already but I've live example so I hope my question may be useful. Here I've custom plugin for jQuery:
(function($){
jQuery.alertSay = function(options){
var options = $.extend({say:'open'}, options};
alert('We are currently ' + say + '!');
};
})(jQuery);
connected to the main index.html:
$(document).ready(function() {
$.alertSay({
say: 'on vacations'
});
});
And it doesn't work because of options, cause if I use simple method without any options, like this:
(function($){
jQuery.alertSay = function(){
alert('We are currently on vacations!');
};
})(jQuery);
It works just fine with the link like:
$(document).ready(function() {
$.alertSay();
});
Due to my poor knowledge in jQuery I'm unable to detect where my mistake is and it would be so nice from you to help me if possible. Thank you!
UPD:
Thank you for your replies but unfortunately replacing
alert('We are currently ' + say + '!');
with
alert('We are currently ' + options.say + '!');
change nothing, no alert at all. But I've some errors:
Uncaught SyntaxError: Unexpected token } hallo.js:3
Uncaught TypeError: Object function (a,b){return new p.fn.init(a,b,c)} has no method 'alertSay' (in the html on string $.alertSay({)
In your 1st snippet code replace say with options.say
(function($){
jQuery.alertSay = function(options){
var options = $.extend({say:'open'}, options); // some error here
alert('We are currently ' + options.say + '!');
};
})(jQuery);
jsfiddle: DEMO
The problem is here:
alert('We are currently ' + say + '!');
// -------------------------^
You want
alert('We are currently ' + options.say + '!');
The first one is looking for a variable called say. The second is looking for the property say on your options object.
You also have a } where you mean to have a ):
var options = $.extend({say:'open'}, options};
// -----------------------------------------^
should be
var options = $.extend({say:'open'}, options);
With those two fixes, it runs fine (source).
Related
The codes to add download links automatically to audio embeds used to work, and now, suddenly i get errors saying Uncaught TypeError: $ is not a function...
i am totally confused as to why
Sample link is https://mpmania.com/download-mp3/wizkid-ghetto-love-audio/
Ive used troubleshooting mode, deactivated all plugins, updated outdated ones, probably someone can help with rewriting these codes to work
$( document ).ready(function() {
$('audio').each(function( index ) {
var source = $(this).find('source').attr('src');
if ( source != '' ) {
$(this).after('<a href="' + source + '" class="audio-download" download>Download (Alternative)</a>');
}
});
});
I basically expect it to work as it used to
Expanding on my comment above, your code should look like this:
jQuery(function($) {
$('audio').each(function(index) {
var source = $(this).find('source').attr('src');
if (source != '') {
$(this).after('<a href="' + source + '" class="audio-download" download>Download (Alternative)</a>');
}
});
});
He guys i am having this problem with loading a page through jQuery ajax.
This is my first time trying to do something with jQuery and ajax calls.
However a simple load doesn't show me anything also i don't know how to show all the error's it generates if it generates error's.
Any what i want is to retrieve the pages html data, would appreciate it if somebody can tell me what I'm doing wrong.
I'm using jQuery 1.10.2
This is the code I am trying to use.
$(document).ready( function(){
loadPage();
});
function loadPage(){
var obj = {};
obj.test=true;
obj.something=true;
$.ajax({
type:'POST',
url:'http://www.w3.org/',
data:obj,
success:onLoadComplete,
error:onError
});
};
function onError(){
console.log($(this));
}
function onLoadComplete(pdata, pstatus, pxhr){
console.log("respons: " + pdata);
console.log("text status: " + pstatus);
console.log("xhr: " + pxhr);
}
I'm having some problems updating a jquery progress bar. This progress bar isn't in the document during the page load, I'm adding it just when the user click on a button, ding something like this:
$(this).parent().append('<div class="progressbar"></div>');
$(this).parent().children('div.progressbar').show();
$(this).parent().children('div.progressbar').progressbar({value: 20});
then, using a timeout, I'm trying to update it
function updateProgressBar() {
$('.progressbar').each(function() {
myNewValue = getNewValue();
$(this).progressbar('value', 50);
});
setTimeout('updateProgressBar()', 5000);
}
setTimeout('updateProgressBar()', 5000);
the debug console complains saying: "Uncaught: cannot call methods on progressbar prior to initialiaztion: attempted to call method 'value'"
Googling here I found that the problem could be related to the inizialization of the progress bar after the loading of the page
Could someone help me?
Thanks in advance
-- edit --
thanks Bryan, I'm trying your solution but i doesn't work for me
Now I've this code
function startProgress() {
$(this).parent().append('<div class="progressbar"></div>');
$(this).siblings('.progressbar').show();
$(this).siblings('.progressbar').progressbar({value: 0});
function updateProgress() {
$('.progressbar').each(function() {
myNewValue = getNewValue($(this).parent().parent().attr('id'));
$(this).progressbar('value', myNewValue);
});
setTimeout('updateProgress', 5000);
}
setTimeout('updateProgress', 5000);
}
The console is sayng there's no updateProgress defined
-- edit --
many many thanks!!!
Now i've a quite definitive version that works...
Here my current code
if($(this).siblings('.progressbar').size() == 0) {
$(this).parent().append('<div class="progressbar"/>');
$(this).siblings('.progressbar').progressbar({value: 0});
}
$(this).siblings('.progressbar').show();
function updateProgress() {
$('.progressbar').each(function() {
myParams = 'service=' + $(this).parent().parent().attr('id') + '&content=' + $(this).parent().attr('id')
myUrl = '/datacast/content_progress/?' + myParams;
theValue = $(this).progressbar('value');
$.get(myUrl, {}, function(aReply) {
myData = aReply.split(' ');
myItemId = myData[0];
myValue = parseInt(myData[1]);
try {
$(".item[id = " + myItemId + "]").children(".progressbar").progressbar('value', myValue);
}
catch(myError) {
//alert(myError);
}
})
});
setTimeout(updateProgress, 5000);
}
setTimeout(updateProgress, 5000);
As you can see I've add a control if there is already a progress bar as i pass thorough that code several times.
The progress bar is updated every time, but the console complains saying "TypeError: Cannot call method 'apply' of undefined", so I had to add the try block with an empty catch body to drop the error. The page works but it could be interesting if you have an idea why there's that error
Had the same problem
Apparently you must use the format progressbar({value:30}) the first time
If you use progressbar(value,30) the first time then you get this exception.
Ok, I can't believe I missed that. The problem is that you're passing a string to the setTimeout function. This will cause it to lookup the name of the function in global scope, which it's not.
Change both of these calls:
setTimeout('updateProgress', 5000);
to
setTimeout(updateProgress, 5000);
Make sure that you're using the exact same selector in your update method as in the initialization method.
In the provided code, you're doing something like $(this).parent().children().find('.progressbar') and then in the update you're just doing $('.progressbar'). That second call could potentially return items that the first one didn't, and those items wouldn't have a progress bar initialized.
This code worked fine for me:
$(function(){
$('body').append('<div class="progress"></div>');
var val = 10;
$('.progress').progressbar({value:val});
function updateProgress() {
val += 10;
$('.progress').progressbar('value', val);
if(val < 100)
setTimeout(updateProgress, 1000);
}
setTimeout(updateProgress, 1000);
});
Also, remember that you don't actually need that call to each() as jquery methods should automatically apply to all elements matched with that selector.
Example:
$('.red').each(function(){ $(this).css({color:'red'}); });
is redundant, and the same can be achieved with:
$('.red').css({color:'red'});
Oh, and here's a freebie:
$(this).parent().children().find('.progressbar')
can be shortened to: $(this).siblings('.progressbar')
I'm creating a plugin for jQuery. I wont attempt to explain the plugin here, so lets say for simplicity that my plugin opens an alert when you click on the targeted element. Here is a simple version of my plugin.
(function($) {
// Options
var defaults = {
message: 'Default message'
};
var options = $.extend(defaults, options);
$.fn.jAlert = function(options) {
return this.each(function(){
var $this = $(this);
$this.click(function(){
alert(options.message);
});
});
};
})(jQuery);
I can get that far. It works great. However, if I call my plugin like this:
$('h1.simon').plugin({ message: 'Hello ' + $(this).attr('class') });
The message returns as 'Hello undefined', I'd prefer it to be 'Hello simon' (the class of the H1 tag).
I'm sure this is the simplest thing to do, but I'm not even sure what I should be Googling to find the solution.
Any help would be greatly appreciated!
Cheers,
Will
Update:
After playing about a bit, this seems to work... And I have no idea why! I don't think I really understand scope yet. I think I'll go do some reading.
$('h1.simon').click(function(){
$(this).jAlert({
icon: 'Hello ' + $(this).attr('class')
});
});
Save a reference to the element:
var $el = $('h1.simon');
$el.plugin({ message: 'Hello ' + $el.attr('class') });
Otherwise this refers to window which doesn't have a class.
If you want to be able to use this for convenience, you could allow message to accept a function that returns the value you want to display.
Try it out: http://jsfiddle.net/9hyJc/
(function($) {
$.fn.jAlert = function(options) {
// Options
var defaults = {
message: 'Default message'
};
var options = $.extend(defaults, options);
return this.each(function(){
var $this = $(this);
$this.click(function(){
if($.isFunction(options.message)) {
// If it is a function, call it,
// setting "this" to the current element
alert(options.message.call(this));
} else {
// Otherwise, assume it is a string
alert(options.message);
}
});
});
};
})(jQuery);
$('h1.simon').jAlert({ message: function() { return 'Hello ' + $(this).attr('class'); } });
at the time you are calling the plugin and passing the options .. this refers to window and NOT the element as you seem to expect
I have some javascript code on my webpage that is loading some divs onto the page. I also want to add onmouseenter, and onmouseleave event handlers to each div. I am using jquery to add these handlers, but i get the error:
"Property '$' of object [object DOMWindow] is not a function"
My code looks like this, it is in a for loop:
var newItem = document.createElement('div');
newItem.innerHTML = results[i];
newItem.setAttribute("id", "resultDiv_" + i.toString());
dropDown.appendChild(newItem);
//Error on next line...
$("resultDiv_" + i.toString()).bind("mouseenter", function() {
$("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
});
Does anyone have any ideas why i am getting this error, or even what the error means?
Try replacing all occurrences of $ with jQuery.
Also the selector $("resultDiv_" + i.toString()) won't likely return any elements. You probably meant: $("#resultDiv_" + i.toString())
And finally make sure this code is executed when the DOM is ready i.e. inside:
jQuery(function() {
// Put your code here
});
Are you sure that jQuery is properly loaded? Could it be a conflict with another javascript library?
(function ($) {
// All your code here
})(jQuery);
This fixed the problem for me.
What about trying this?
var newItem = document.createElement('div');
newItem.innerHTML = results[i];
newItem.setAttribute("id", "resultDiv_" + i.toString());
dropDown.appendChild(newItem);
//Error on next line...
$("resultDiv_" + i.toString()).mouseenter( function() {
$("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
});
Or make sure that $("resultDiv_" + i.toString()) is not null. Use Firebug to inspect the element.
You might as well try this:
var newItem = jQuery('<div id="' + "resultDiv_" + i.toString() + '">+ results[i] + '</div');
jQuery(dropDown).append(newItem);
//Error on next line...
newItem.mouseenter(function(){
jQuery(this).css( 'background-color', 'blue');
});
or perhaps jQuery.noConflict will solve this.