Form element Iteration, in Javascript - javascript

I've been working on a code snippet for a template module that I have been creating and I've hit a wall so to speak. I'm trying to loop through all textareas on my page, and apply formatting with some very basic validation.
Javascript is not my strongest suit but I can understand it to a point, my question is how do I collect the ID's and then use them to apply the formatting.
For example,
for each (textarea)
{
collect character restriction from html
display character restriction in a formatted manner
}
I have included my JSFiddle which I have been using to build this snippet.

I would suggest creating a prototype class for this, that can be extended to do other things aswell:
var CharWatcher = function(input){
this.max = input.getAttribute('max-length');
this.input = input;
input.onKeyDown = this.update.bind(this);
this.wrapper = document.createElement('div');
this.wrapper.innerHTML = 'Chars left: '+ (max - input.value.length);
/* style wrapper element */
/* append around input */
};
CharWatcher.prototype = {
update: function(){
this.wrapper.innerHTML = 'Chars left: ' + (this.max - this.input.value.length);
}
};
/* Somewhere else */
var textareas = document.getElementsByTagName('textarea');
for(var i = 0, l = textareas.length; i < l; i++)
new CharWatcher(textareas[i]);

I've based on #FodorZoltán's class. My class does now:
append the counter below the textarea;
position the counter in the below part of the textarea;
Yeah, I'm lazy and the code has grown up. I added some events and renamed the class name to "TextAreaRanger". It's working here:
var TextAreaRanger = function(input) {
this.MAX = parseInt(input.getAttribute('maxlength'));
this.INPUT = input;
// add input events
input["oncut"] =
input["onpaste"] =
input["onkeydown"] =
input["onkeyup"] = this.update.bind(this);
// create wrapper element
this.wrapper = document.createElement('div');
this.wrapper.innerHTML = 'Chars left: '+ (this.MAX - input.value.length);
/* input parent element */
var ipar = input.parentNode;
// find input's i
for (var i = 0, el; el = ipar.children[i]; i ++) {
if(el === input) break;
}
// append wrapper below the input
if (ipar.children[++i]) {
ipar.insertBefore(this.wrapper, ipar.children[i]);
} else ipar.appendChild(this.wrapper);
/* stylize wrapper */
this.wrapper.style.position = "relative";
this.wrapper.style.color = '#f00';
this.wrapper.style.fontSize = '11px';
this.wrapper.style.left = (input.offsetLeft + (input.offsetWidth - 100)) + "px";
this.wrapper.style.top = (-parseInt(this.wrapper.style.fontSize) * 2) + "px";
};
// Update the counter
TextAreaRanger.prototype["update"] = function() {
this.wrapper.innerHTML = 'Chars left: ' + (this.MAX - this.INPUT.value.length);
};

Related

How to get the access to the id from my element?

I'm trying to learn to use class.
And I have a class that creates a div element for me.
Which got an id.
And, I have a function that overrides the id, but how do I do that?
My Class:
var count = 0;
class Element {
constructor(width,height,into) {
this.createElement("",into,width,height)
}
createElement(type,into,width,height) {
if (!type)
type = "div"
let element = document.createElement(type);
element.style.width = width;
element.style.height = height;
element.style.border = 1+"px solid"
element.style.position = "relative";
element.name = "element" + count;
document.querySelector(into).append(element)
count ++
}
addID(name,clasName) {
clasName = clasName.id
return document.querySelector(`.+${clasName}`) = this.name
}
}
My Script:
var test = new Element(100 + "%", 100 + "px", "body");
test.addID("MainDiv", test.id)
Thx for u help
I think what you're looking for is this.className = className.id;. The question is a bit vague but the this keyword will give you a reference to your class instance.
Problems & solution:
Element Class not return id .So test.id is undefined one.So you must declare with this.id for Better understand in class refer doc
Add embedded the id with element using element.id=this.id in createElement function
And document.querySelector target classname selector.But if you are passing id use with # instead of .
And return statement in addID is not working .Because You are passing the value to element .Use textContent for pass value to div
var count = 0;
class Element {
constructor(width,height,into) {
this.createElement("",into,width,height)
this.id='one';
this.name="is this name"
}
createElement(type,into,width,height) {
if (!type)
type = "div"
let element = document.createElement(type);
element.style.width = width;
element.style.height = height;
element.style.border = 1+"px solid"
element.style.position = "relative";
element.name = "element" + count;
element.id=this.id;
document.querySelector(into).append(element)
count ++
}
addID(name,clasName) {
clasName = clasName.id;
document.querySelector(`#${clasName}`).textContent = name
}
}
var test = new Element(100 + "%", 100 + "px", "body");
test.addID("MainDiv", test.id)
Solution
first of all I had to use the referrer this.!
For adding or removing classnames or id, you also can manipulate your created element in progress.
'use strict'
var count = 0;
class Element {
constructor(type, width, height, into, functionName, value) {
if (into)
this.createElement(type, into, width, height, functionName, value)
}
createElement(type, into, width, height, functionName, value) {
if (!type)
type = "div"
this.element = document.createElement(type);
this.element.style.width = width;
this.element.style.height = height;
this.element.style.border = 1 + "px solid"
this.element.style.position = "relative";
// this.element.id = this.id
if (type == "button")
this.extendButton(this.element, functionName, value);
document.querySelector(into).append(this.element);
count++;
}
extendButton(element, functionName, value) {
this.element.onclick = functionName;
this.element.innerHTML = value;
}
addID(name, clasName) {
return this.element.id = name
}
} //END
Script:
var test = new Element("",100 + "%", 100 + "px", "body");
test.addID("try");
test.addID("MainDiv")
var test2 = new Element("",80 + "%", 80 + "px", "#MainDiv");
test2.addID("harry");
var buttonTest = new Element("button","","","#MainDiv","showOutgoings","testet")
Guys thank you for your suggestion =)

JavaScript mouseover/mousemove cusor postion without clicking in input text box

I'm attempting to combine a JavaScript mechanism for auto placing the users cursor inside of an input box through the mouseover and mousemove listeners.
I have an almost perfect working example here: http://codepen.io/anon/pen/doxNLm?editors=101
var current_element = document.getElementById("hover");
current_element.onmousemove = function showCoords(evt) {
var form = document.forms.form_coords;
var parent_id = this.id;
form.parentId.value = parent_id;
form.pageXCoords.value = evt.pageX;
form.pageYCoords.value = evt.pageY;
form.layerXCoords.value = evt.layerX;
form.layerYCoords.value = evt.layerY;
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
var element_base_browser_styles = window.getDefaultComputedStyle(current_element);
var total_text_pixal_length = getTextWidth(current_element.value, element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
var add_char_pixal_lengths = 0;
var myStringArray = current_element.value.split('');
var arrayLength = myStringArray.length;
for (var i = 0; i <= arrayLength; i++) {
var get_char_value = getTextWidth(myStringArray[i], element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
add_char_pixal_lengths = add_char_pixal_lengths + (get_char_value) + 1.311111111111; //every char value is added together.
// console.log("Total: " + x);
if ((add_char_pixal_lengths)> (evt.layerX)) {
this.setSelectionRange(i, i);
add_char_pixal_lengths = 0;
break;
}
}
}
current_element.onmouseover = function() {
this.focus()
}
The problem I'm having is like Geosynchronous orbit; the cursor shifts out of place sometimes a few pixels (left or right). My calculation probably sucks, but I'm not sure canvas is really the best way to do the measurement? Is there a better way?
mousemove listener to receive element cursor coordinates from e.pageX
font style using window.getComputedStyles(input_element)
arr.split('') from input_element.text string: x = ['a','b','c']
'for loop' the array, generate a canvas and measure each characters width
add all char widths one by one until the value is greater than e.pageX
set the 'for loop' iterate as the setSelectionRange(i, i)
Any help or suggestions on making this better would be appreciated. Thanks!

how to access innerHTML of button created dynamically through JavaScript

This is a JavaScript function used for creating dynamic buttons. I want to access innerHTML of button.
function mynumber() {
var i,j = 1, num = 0; # i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
do {
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON"); # create button using javascript
var txt = document.createTextNode(num++); # creat text on button
btn.appendChild(txt); # attached text on button
btn.id = ('obj'+ k++) ;
document.getElementById("btnsize").appendChild(btn); # atache button with text in div
}
var next = document.createElement("BR");
document.getElementById("btnsize").appendChild(next);
j++;
}
while(j<4)
}
("btn").click(function()
{
var val = document.getElementById(this.id).innerHTML;
document.getElementById("demo").value = val;
})
You can apply css class to the button as shown in https://jsfiddle.net/3u71kzrh/
Declare a style as below in your stylesheet or between the <style> and </style> tag in the html <head>.
.aClassName{
width:40px;
height:40px;
}
Add the following line just below the code where you create the button element.
btn.className = "aClassName";
use below script in your script code where "100" is variable whatever you want to give but that would be a number ;)
btn.style.width="100px"
btn.style.height="100px"
First of all, I'd change your <button>-creation script to the following:
function mynumber () {
// a reference to the element to which we want
// to add the newly-created <button> elements:
var appendTo = document.getElementById('btnsize'),
// creating a document fragment to contain
// the elements to be added; to prevent the
// document from redrawing every time an
// element is added:
fragment = document.createDocumentFragment(),
// creating a <button> element:
button = document.createElement('button'),
// creating a <br> element:
br = document.createElement('br'),
// initialising an empty variable, for
// use within the loop:
clone;
// you want nine buttons, so use one loop
// that will run nine times:
for (var i = 0; i < 9; i++) {
// using the empty variable to
// hold the cloned <button> element:
clone = button.cloneNode();
// setting the text of the <button>
// to the current index/iteration
// (i) of the loop:
clone.textContent = i;
// appending the cloned <button>
// to the document fragment:
fragment.appendChild(clone);
// we want rows of three, but
// JavaScript is zero-based, so
// we add 1 to i, and check the
// remainder of the division by
// 3; if it's zero the number is
// evenly-divisible by 3 therefore
// it's time to add a <br>:
if ((i+1)%3 === 0) {
// appendin a cloned <br> element:
fragment.appendChild(br.cloneNode())
}
}
// appending the fragment to the
// container element:
appendTo.appendChild(fragment);
}
// calling the function:
mynumber();
function mynumber() {
var appendTo = document.getElementById('btnsize'),
fragment = document.createDocumentFragment(),
button = document.createElement('button'),
br = document.createElement('br'),
clone;
for (var i = 0; i < 9; i++) {
clone = button.cloneNode();
clone.textContent = i;
fragment.appendChild(clone);
if ((i + 1) % 3 === 0) {
fragment.appendChild(br.cloneNode())
}
}
appendTo.appendChild(fragment);
}
mynumber();
<div id="btnsize"></div>
External JS Fiddle demo, for experimentation.
But, because I like to be able to change things – and this also helps address your sizing requirement – I'd amend that to the following, which allows you to call the function, and supply some user-defined options:
// the 'opts' is an Object, containing
// user-defined settings:
function mynumber(opts) {
// these are the defaults:
var settings = {
'container': 'btnsize',
'elements': 'button',
'elementClass': 'newButton',
'height': 'equal',
'width': 'equal',
'rows': 3,
'cols': 3
};
// here we iterate over the properties in the
// opts Object, using for...in:
for (var property in opts) {
// if the object's property is user-defined:
if (opts.hasOwnProperty(property)) {
// we update the settings property to
// match (note: no sanity-checking):
settings[property] = opts[property];
}
}
// finding the element to which we're appending the
// content; using the settings.container property
// (which should contain the 'id' of the element,
// as we're using document.getElementById()):
var appendTo = document.getElementById(settings.container),
fragment = document.createDocumentFragment(),
// 'button' is perhaps a misnomer, since we're creating
// whatever element the user defined, with the
// settings.elements property:
button = document.createElement(settings.elements),
br = document.createElement('br'),
clone;
// if there is a class-name set for the created elements,
// we set that on the created-element (which will be
// copied to all clones, in the loop):
if (settings.elementClass) {
button.classList.add(settings.elementClass);
}
// if the settings.height property is not 'equal', and
// the settings.height can be parsed as a number (a
// naive check, and we're not validating units):
if (settings.height !== 'equal' && parseFloat(settings.height)) {
// we set the height of the created element to
// the value of the settings.height property:
button.style.height = settings.height;
}
// As above, but for height:
if (settings.width !== 'equal' && parseFloat(settings.width)) {
button.style.width = settings.width;
}
// iterating from 0 to the result of multiplying the
// required number of rows by the required number of columns:
for (var i = 0, len = (settings.rows * settings.cols); i < len; i++) {
clone = button.cloneNode();
clone.textContent = i;
fragment.appendChild(clone);
if ((i + 1) % settings.cols === 0) {
fragment.appendChild(br.cloneNode())
}
}
appendTo.appendChild(fragment);
// To avoid running the same test, in subsequent
// if assessments, we create a couple of Booleans
// to test whether settings.width, or
// settings.height, were set to the string 'equal':
var widthEqual = settings.width === 'equal',
heightEqual = settings.height === 'equal';
// if either of those assessments returned true:
if (widthEqual || heightEqual) {
// we find all the elements contained within the
// appended node (to which the elements were
// appended) that have the tagName of the
// created elements:
var appended = appendTo.getElementsByTagName(settings.elements),
// we get the width, and height, of the last
// of those elements - on the assumption that
// that element will have the highest, and
// therefore longest/largest number:
width = appended[appended.length - 1].clientWidth,
height = appended[appended.length - 1].clientHeight;
// if both settings.width and settings.height were
// set to 'equal':
if (widthEqual && heightEqual) {
// we use Function.prototype.call(), to apply
// Array.prototype.forEach() to the Array-like
// NodeList returned by document.getElementsByTagName()
// (from earlier):
Array.prototype.forEach.call(appended, function (btn) {
// btn - the first (and, here, only) argument
// to the anonymous function is the array-
// element over which we're iterating:
// setting the width and height of the
// current element to be equal to the
// found width/height of the last
// element:
btn.style.width = width + 'px';
btn.style.height = height + 'px';
});
// otherwise, if only the width was 'equal':
} else if (widthEqual) {
// As above, setting only the width:
Array.prototype.forEach.call(appended, function (btn) {
btn.style.width = width + 'px';
});
// As above, addressing only the height:
} else if (heightEqual) {
Array.prototype.forEach.call(appended, function (btn) {
btn.style.height = height + 'px';
});
}
}
}
// calling the function, using only the defaults:
mynumber();
// calling the function, setting
// custom values:
mynumber({
'container' : 'anotherElement',
'rows' : 5,
'cols': 4,
'elementClass': 'arbitraryClassName'
});
// calling the function, this time
// explicitly setting the height
// and width:
mynumber({
'container' : 'more',
'elements' : 'span',
'width' : '3em',
'height' : '2em'
});
function mynumber(opts) {
var settings = {
'container': 'btnsize',
'elements': 'button',
'elementClass': 'newButton',
'height': 'equal',
'width': 'equal',
'rows': 3,
'cols': 3
};
for (var property in opts) {
if (opts.hasOwnProperty(property)) {
settings[property] = opts[property];
}
}
var appendTo = document.getElementById(settings.container),
fragment = document.createDocumentFragment(),
button = document.createElement(settings.elements),
br = document.createElement('br'),
clone;
if (settings.elementClass) {
button.classList.add(settings.elementClass);
}
if (settings.height !== 'equal' && parseFloat(settings.height)) {
button.style.height = settings.height;
}
if (settings.width !== 'equal' && parseFloat(settings.width)) {
button.style.width = settings.width;
}
for (var i = 0, len = (settings.rows * settings.cols); i < len; i++) {
clone = button.cloneNode();
clone.textContent = i;
fragment.appendChild(clone);
if ((i + 1) % settings.cols === 0) {
fragment.appendChild(br.cloneNode())
}
}
appendTo.appendChild(fragment);
var widthEqual = settings.width === 'equal',
heightEqual = settings.height === 'equal';
if (widthEqual || heightEqual) {
var appended = appendTo.getElementsByTagName(settings.elements),
width = appended[appended.length - 1].clientWidth,
height = appended[appended.length - 1].clientHeight;
if (widthEqual && heightEqual) {
Array.prototype.forEach.call(appended, function(btn) {
btn.style.width = width + 'px';
btn.style.height = height + 'px';
});
} else if (widthEqual) {
Array.prototype.forEach.call(appended, function(btn) {
btn.style.width = width + 'px';
});
} else if (heightEqual) {
Array.prototype.forEach.call(appended, function(btn) {
btn.style.height = height + 'px';
});
}
}
}
mynumber();
mynumber({
'container': 'anotherElement',
'rows': 5,
'cols': 4,
'elementClass': 'arbitraryClassName'
});
mynumber({
'container': 'more',
'width': '3em',
'height': '2em'
});
button {
font-size: 2em;
}
.arbitraryClassName {
color: #fff;
border: 1px solid limegreen;
text-shadow: 0 0 2px #000;
}
<div id="btnsize"></div>
<div id="anotherElement"></div>
<div id="more"></div>
External JS Fiddle demo, for experimentation/developement.
Now, to address your question in the simplest terms possible, using the code you originally posted (incidentally, in JavaScript, the # character is not valid for comments; it's a syntax error: Uncaught SyntaxError: Unexpected token ILLEGAL), you could simply use CSS such as below:
function mynumber() {
var i, j = 1,
num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
do {
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON"); // create button using javascript
var txt = document.createTextNode(num++); // creat text on button
btn.appendChild(txt); // attached text on button
document.getElementById("btnsize").appendChild(btn); // atache button with text in div
}
var next = document.createElement("BR");
document.getElementById("btnsize").appendChild(next);
j++;
}
while (j < 4)
}
mynumber();
button {
width: 3em;
height: 4em;
}
<div id="btnsize"></div>
External JS Fiddle demo.
This CSS, of course, matches all <button> elements in the page; however you could amend the selector to be more specific to only those <button> elements within the btnsize element:
#btnsize button {
width: 3em;
height: 2em;
color: #f00;
}
function mynumber() {
var i, j = 1,
num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
do {
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON"); // create button using javascript
var txt = document.createTextNode(num++); // creat text on button
btn.appendChild(txt); // attached text on button
document.getElementById("btnsize").appendChild(btn); // atache button with text in div
}
var next = document.createElement("BR");
document.getElementById("btnsize").appendChild(next);
j++;
}
while (j < 4)
}
mynumber();
#btnsize button {
width: 3em;
height: 4em;
color: #f00;
}
<div id="btnsize"></div>
<button>Just to demonstrate that I'm not being styled</button>
External JS Fiddle demo.
Or you could add a class-name while you create your <button> elements:
#btnsize button {
width: 3em;
height: 2em;
color: #f00;
}
function mynumber() {
var i, j = 1,
num = 0; // i used for making three buttons in row and j used for repeat same process no of time and num is int text on button
do {
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON"); // create button using javascript
// adding a class-name:
btn.classList.add('buttonClassName');
var txt = document.createTextNode(num++); // creat text on button
btn.appendChild(txt); // attached text on button
document.getElementById("btnsize").appendChild(btn); // atache button with text in div
}
var next = document.createElement("BR");
document.getElementById("btnsize").appendChild(next);
j++;
}
while (j < 4)
}
mynumber();
.buttonClassName {
width: 3em;
height: 4em;
color: #f00;
}
<div id="btnsize"></div>
<button>Just to demonstrate that I'm not being styled</button>
External JS Fiddle demo.
References:
Array.prototype.forEach().
document.createDocumentFragment().
document.createElement().
document.getElementById().
Element.classList.
for...in.
Function.prototype.call().
HTMLElement.style.
% (modulo) operator.
Node.appendChild().
Node.cloneNode().
Node.textContent.
Object.hasOwnProperty().

How to display only one image in ezpublish JS slider

I'm a beginner php developer, and have a shockingly poor fluency in Javascript. An ezpublish website I'm working on has this slider in as a default piece of code, but it displays three items. How can I edit it to show only 1 item? The code is:
(function() {
YUI( YUI3_config ).use( 'node', 'event', 'io-ez', function(Y, result) {
Y.on('domready', function(e) {
var offset = 0;
var limit = 1;
var total = {$block.valid_nodes|count()};
var handleRequest = function(e) {
var className = e.target.get('className');
if ( className == 'carousel-next-button' ) {
offset += 1;
if ( offset > total )
offset = 0;
}
if ( className == 'carousel-prev-button' ) {
var diff = total - offset;
if( offset == 0 )
offset = 0;
else
offset -= 1;
}
var colContent = Y.Node.all('#block-3 .col-content');
colContent.each(function(n, e) {
n.addClass('loading');
var height = n.get('region').bottom - n.get('region').top;
n.setStyle('height', height + 'px');
n.set('innerHTML', '');
});
var data = 'http_accept=json&offset=' + offset;
data += '&limit=' + limit;
data += '&block_id={$block.id}';
Y.io.ez( 'ezflow::getvaliditems', { on: { success: _callBack
}, method: 'POST', data: data } );
};
var _callBack = function(id, o) {
if ( o.responseJSON !== undefined ) {
var response = o.responseJSON;
var colContent = Y.Node.all('#block-{$block.id} .col-content');
for(var i = 0; i < colContent.size(); i++) {
var colNode = colContent.item(i);
if ( response.content[i] !== undefined )
colNode.set('innerHTML', response.content[i] );
}
}
};
var prevButton = Y.one('#block-{$block.id} input.carousel-prev-button');
prevButton.on('click', handleRequest);
var nextButton = Y.one('#block-{$block.id} input.carousel-next-button');
nextButton.on('click', handleRequest);
});
});
})();
</script>
A hand with this would be great x
Looks to me like this code loads each item after the user clicks prevButton or nextButton. So the simplest way to force only a single item to display is probably to hide those buttons.
Without the markup it's hard to say what the optimal solution is, but I would try to find out what makes the particular markup you're working with into a carousel (I'd guess a class containing "carousel") and remove that so that it's just a single item without the carousel functionality.
For what it's worth, this question is not specific to eZ Publish or PHP so I'd consider removing those tags.

Bind events to all elements in class instead of just to one id

I developed this interaction / script that scales whatever element is passed to it and if that element is pinched in on, it scales down / less.
This is how the script is initialised ( passing two arguments the container and the item to be scaled / transformed:
$(function(){
var zoom = new collapse('#zoom','#zoom :first');
var zoom2 = new collapse('#zoom2','#zoom2 :first');
var zoom3 = new collapse('#zoom3','#zoom3 :first');
});
It works fine as above on single IDs, but I need it to work on a class.
I tried this:
$(function(){
var zoom = new collapse('#zoom','.polaroid');
});
But that causes the whole script not to work because all the elements in that class are being passed instead of one as with an id.
This would only select the first item in the class so it won't work:
$(function(){
var zoom = new collapse('#zoom','.polaroid :first');
});
How can I change my script so that it is applied to all members of the .polaroid class in the #main container?
Here is my script:
function collapse(container, element){
container = $(container).hammer({
prevent_default: true,
scale_threshold: 0
});
element = $(element);
var displayWidth = container.width();
var displayHeight = container.height();
var MIN_ZOOM = 0;
var MAX_ZOOM = 1;
var scaleFactor = 1;
var previousScaleFactor = 1;
var startX = 0;
var startY = 0;
var translateX = 0;
var translateY = 0;
var previousTranslateX = 0;
var previousTranslateY = 0;
var time = 1;
var tch1 = 0,
tch2 = 0,
tcX = 0,
tcY = 0,
toX = 0,
toY = 0,
cssOrigin = "";
container.bind("transformstart", function(event){
e = event;
tch1 = [e.touches[0].x, e.touches[0].y],
tch2 = [e.touches[1].x, e.touches[1].y];
tcX = (tch1[0]+tch2[0])/2,
tcY = (tch1[1]+tch2[1])/2;
toX = tcX;
toY = tcY;
var left = $(element).offset().left;
var top = $(element).offset().top;
cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
});
container.bind("transform", function(event){
scaleFactor = previousScaleFactor * event.scale;
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
transform(event);
});
container.bind("transformend", function(event){
previousScaleFactor = scaleFactor;
if(scaleFactor > 0.42){
$(element).css('-webkit-transform', 'scaleY(1.0)').css('transform', 'scaleY(1.0)');
}
});
function transform(e){
var cssScale = "scaleY("+ scaleFactor +")";
element.css({
webkitTransform: cssScale,
webkitTransformOrigin: cssOrigin,
transform: cssScale,
transformOrigin: cssOrigin,
});
if(scaleFactor <= 0.42){
$(element).animate({height:0}, function(){
$(this).remove();
});
}
}
}
Wrap it as a jquery plugin:
$.fn.collapse = function(filter) {
return this.each(function(){
collapse(this,filter);
});
}
$("#zoom,#zoom1,#zoom2").collapse(".polaroid");
or if each of the zoom elements had a common class,
$(".zoomel").collapse(".polaroid");
You have to run collapse for each element.
element = $(element);
element.each(function(){
//each element would be this here
var $this= $(this);
//do whatever you want with $this
})

Categories

Resources