How to create simple jQuery plugin? - javascript

This test plugin, is supposed to work like this: When an element is clicked, it moves down. Simple as that.
jQuery.fn.moveDown = function(howMuch){
$(this).css("border", "1px solid black");
$(this).click(function(){
$(this).css("position", "relative");
$(this).animate({top: '+='+howMuch});
});
}
The problem is, when an element is clicked, it not only moves the clicked element but also ALL the other elements which the plugin was applied to.
What is the solution for this?

For plugin authoring try this way, much more solid:
Edit:
Here is working jsFiddle example.
PLUGIN:
(function($){
$.fn.extend({
YourPluginName: function(options) {
var defaults = {
howMuch:'600',
animation: '',//users can set/change these values
speed: 444,
etc: ''
}
};
options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var button = $('a', $this);// this represents all the 'a' selectors;
// inside user's plugin definition.
button.click(function() {
$this.animate({'top':options.howMuch});//calls options howMuch value
});
});
})(jQuery);
USER'S DOCUMENT:
$(function() {
$('#plugin').YourPluginName({
howMuch:'1000' //you can give chance users to set their options for plugins
});
});
<div id="plugin">
<a>1</a>
<a>2</a>
<a>3</a>
</div>

Here i want to suggest steps to create simple plugin with arguments.
JS
(function($) {
$.fn.myFirstPlugin = function( options ) {
// Default params
var params = $.extend({
text : 'Default Title',
fontsize : 10,
}, options);
return $(this).text(params.text);
}
}(jQuery));
Here, we have added default object called params and set default values of options using extend function. Hence, If we pass blank argument then it will set default values instead otherwise it will set.
HTML
$('.cls-title').myFirstPlugin({ text : 'Argument Title' });
Read more: How to Create JQuery plugin
Original answer Here i want to suggest steps to create simple plugin with arguments

If you have Node.js installed you can use create-jquery-plugin CLI utility. Just run
npx create-jquery-plugin
Or, you can clone the jquery-plugin-boilerplate
to get started.

Related

JQuery Plugin's Separate Scope for Each Element

I am developing a carousel jquery plugin. I am trying to call with more than one carousel div element like
<div class="carousel-container">...</div>
<div class="carousel-container2">...</div>
...
Where I am calling plugin
$(".carousel-container").mycarousel({
// Properties
});
$(".carousel-container2").mycarousel({
// Properties
});
Plugin Code:
(function($) {
$.fn.mycarousel = function(options) {
var settings = $.extend({
indicators : true,
autoplay : true,
autoplayDir : "forward",
slidesToShow : 1,
slidesToScroll : 1
}, options);
return this.each(function() {
// JavaScript code like constructor function and its prototypes
// variable declarations and initialization
var outerCarouseWidth, imageWidth;
var elements, carousel;
...
// jquery code for selectors, events etc.
var carouselInner = $(".carousel-inner");
var carouselOuter = $(".carousel-outer");
...
$(".next-link").on("click", function(e) {
slide("next", "first");
});
...
});
};
}(jQuery));
Well, right now I am trying to access child elements using $(this) within each function. Like $(this).children()[0].text("abc").
The Problem I am facing here is that, both carousel div elements are sharing the scope of variables, selectors etc. When I slide one carousel, other carousel moves as well and facing some other technical issues. How can I separate the scope of code of jquery plugin for each element with which I am calling this plugin?
Scope the finding of elements to the current element that the plugin is applied upon.
Use carouselEl as the parent selector for all sub elements.
Like this:
```
return this.each(function() {
var carouselEl = $(this);
...
// jquery code for selectors, events etc.
var carouselInner = carouselEl.find(".carousel-inner");
var carouselOuter = carouselEl.find(".carousel-outer");
...
carouselEl.find(".next-link").on("click", function(e) {
slide(carouselEl, "next", "first"); // This must also be scoped.. I cant see the code for this function.
});
...
});
```

My javascript script for changing css don't seem to be working

function normToggle(){
document.getElementById('normToggle').onclick = function(){
if(document.getElementById('normToggle').checked){
document.getElementsByTagName('add').style.verticalAlign= 'baseline';
}else{
document.getElementsByTagName('add').style.verticalAlign= 'super';
}
};
document.getElementsByTagName('add').style.verticalAlign= 'super';
document.getElementById('normToggle').checked = false;
}
So I try to use a checkbox to change the style of the 'add' tags. Their vertical align are super first, then i wnat them to change normal, but they didnt respond. Another javascript from the smae file working just fine.
getElementsByTagName returns a HTML Collection - you'll need to iterate through the collection to change the style of each element in the collection
something like this:
function normToggle() {
var setAlign = function (align) {
[].forEach.call(document.getElementsByTagName('add'), function(tag) {
tag.style.verticalAlign = align;
});
}
document.getElementById('normToggle').addEventListener('click', function() {
setAlign(this.checked ? 'baseline' : 'super');
});
setAlign('super');
document.getElementById('normToggle').checked = false;
}
Looking at the code now, you're unlikely to have elements called <add> !!! Is that some sort of mistake in your HTML?

Looping through generated HTML with jQuery

I know if I wanted to bind events to generated HTML, I'd need to use something like .on(), but I've only used it when binding events like .click().
I'm creating a web app that applys a list of colors. Colors are generated from a JSON file. Once fetched, I add it to the page, with certain information contained in attributes. I'd like to do something with the new generated HTML, which is list-elements. But what console.log() is showing me is there is nothing in the parent ul. Even though on the page I see the newly added content.
Here's the entire code based around it.
var setColors = function(){
getColors = function(){
$.getJSON('js/colors.json', function(colors) {
$.each(colors, function(i, colors) {
//console.log(colors);
$('<li>', {
text: colors['color'],
'name' : colors['color'],
'data-hex' : colors['hex'],
'data-var' : colors['var']
}).appendTo('#picker');
})
});
addColors();
}
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
return getColors();
}
$(function(){
setColors();
});
addColors() is where I'm having trouble with. The error says 'Uncaught TypeError: Cannot read property 'firstChild' of null. How can I work with the newly generated HTML?
You are missing parentheses on the children method:
var el = $('#picker').children();
Also, if you want the addColor method to be executed on the newly generated html, then you must add a call to it after the html is generated, from within the getJSON callback method.
addColors = function(){
var el = $('#picker').children;
$(el).each(function(){
console.log($(this));
});
}
A few issues:
missing end semi-color
missing parentheses on .children()
children() returns a jQuery object, no need for $(el)
Updated:
window.addColors = function(){
var $el = $('#picker').children();
$el.each(function(){
// do stuff here, but could attach each() to above, after children()
});
};

Create instances of function

I have a map with a bunch of buttons that show and hide container div's. I don't want to assign the same code to each button because it's all the same.
I was thinking to create a variable when the button is clicked so it could replace a part in the DIV ID (handler?)
So I could refer to #fiche_8_1980_img_container as #fiche_VARIABLE.
Second part of my question is the animation functions I do are all looking like this:
$('#fiche_8_1980_img_container').animate({"opacity" : 1,}, 150, function() {});
Is there a way to put this in an instance or object so I could call it easier?
Here is a piece of code that I use for the button.
$('#button_8_algiers').click(function() {
$('#fiche_8_1980_img_container').css('visibility','visible');
$('#fiche_8_1980_img_container').animate({"opacity" : 1,}, 150, function() {
});
});
If anyone could point me in the right direction it would be great, I don't know where to start looking...
Thank you
would something like this help?
var ficheHandler = {
animateFiche: function(fiche) {
fiche
.css('visibility','visible');
.animate({"opacity" : 1,}, 150, function() {
});
}
}
$('#button_8_algiers').click(function() {
ficheHandler.animateFiche($('#fiche_8_1980_img_container'));
});
Try this which is basically using the help of jQuery chaining so there is no need to cache the object into local variables.
$('#button_8_algiers').click(function() {
$('#fiche_8_1980_img_container').css('visibility','visible');
.animate({"opacity" : 1,}, 150, function() {
});
});
I'm assuming you have control over the HTML. If you have that many buttons with shared functionality, give them the same CSS class, and add a unique identifier in either the rel or data attributes:
$('a.myButton').click(function(e) {
e.preventDefault();
$('#' + $(this).attr('data-target')).fadeIn(150);
});

Help me move from prototype to jquery

window.onload = function() {
$A($('draggables').getElementsByTagName('p')).each(
function(item) {
new Draggable(
item,
{
revert: true
}
);
}
);
Droppables.add(
'droparea0',
{
hoverclass: 'hoverActive',
onDrop: moveItem
}
);
// Set drop area by default non cleared.
$('droparea0').cleared = false;
}
function moveItem( draggable,droparea){
$(droparea).highlight({startcolor: '#999999', endcolor: '#f3f0ca' });
if (!droparea.cleared) {
droparea.innerHTML = '';
droparea.cleared = true;
}
draggable.parentNode.removeChild(draggable);
droparea.appendChild(draggable);
}
Hi, I'm moving from prototype to Jquery and right now I've being unsuccessfuly able to do the transition and finally need some help. can some pne please help me to translate the above prototype js code to jquery put some comments to it so I can follow? I will really appreciate. Yes, prototype is a bit hard work but until I get my head into jquery completely it will be hard to get that move out of my head.
As already mentioned, jQueryUI is your friend. Given the following HTML:
<div class='draggables'>
<p>Drag1</p>
<p>Drag2</p>
<p>Drag3</p>
</div>
<div id='droparea0'>Drop Zone</div>
You can use the following jQuery and jQueryUI to get something close to what you are doing.
$(document).ready(function() {
$('.draggables p').draggable();
$('#droparea0').droppable({
drop: function(event, ui) {
ui.draggable.detach(); // detach the dragged element from the DOM
$(this).css({'background-color': '#999999'}) // start colour for drop area
.animate({'background-color': '#f3f0ca'}) // animate to final colour
.empty() // clear the contents of the dropzone
.append(ui.draggable); // append the dragged element
ui.draggable.css({top: 0, left: 0}); // reset top/left since it was changed during dragging
}
});
});
Working jsFiddle here: http://jsfiddle.net/2F8YE/
first of all in jQuery you should use $(function(){...}) instead of window.onload (jquery starts here ;D)
just look at the jQueryUI sample http://jqueryui.com/demos/droppable/

Categories