Modular way to use jQuery selectors - javascript

Is there a way to use jQuery selectors in modular way:
var logo = $('.logo', function() {
function show () {
console.log('logo has appeared');
$(this).addClass('logo-animated');
};
function hide() {
console.log('logo has been removed');
};
});
I want to be able to assign selector to variable and have some functions within it that I could be able access from outer it's scope.
NOTICE, that is pseudo code, I just drew you a picture of how I see it.
var selector = $('.someclass',
# here goes functions that I could access from outside;
);
UPDATE
var parallax = function() {
var images = ["http://localhost:8000/static/assets/images/hero-image-welcome.jpeg"];
var selector = $('.parallax-module');
var reload = function() {
console.log('reload')
};
$(selector).each(function(index) {
var image = {};
image.element = $(this);
image.height = image.element.height();
images.push(image);
$(this).css('background-image', 'url(' + images[index] + ')');
});
return {
images: images,
reload: reload()
}
}();
parallax.reload;
console.log(parallax.images[0])
// This goes without error, but isn't right;
var sParallax = $('.parallax-module');
sParallax.addClass('someClass');
// This would cause error;
parallax.addClass('someClass');
In this case I can use parallax public properties and methods, but I can't use selector (as I did in the beginning) without creating a new link to it. I know I can use public properties to access selector, but it's not the way I looking for.

You can just set the variable with your desired selector and then just add functions to that variable
var logo = $('.logo');
logo.show = function () {
console.log('logo has appeared');
$(this).addClass('logo-animated');
}
logo.hide = function () {
console.log('logo has been removed');
}
logo.show();
logo.hide();
JSFIDDLE

You can access through this:
logo.prevObject[0].show()//or hide()

I think I found the way, but it does not look right to me, it is working thought:
var parallax = function() {
var images = ["http://localhost:8000/static/assets/images/hero-image-welcome.jpeg"];
var selector = $('.parallax-module');
var reload = function() {
console.log('reload')
};
$(selector).each(function(index) {
var image = {};
image.element = $(this);
image.height = image.element.height();
images.push(image);
$(this).css('background-image', 'url(' + images[index] + ')');
});
return {
images: images,
reload: reload()
}
}().selector;
With selector reference in the end it is now valid to use parallax variable as simple link to DOM element, as well as to access functions that within it.

Related

Using JQuery on a window reference?

Can you use JQuery on a window reference? I have tried the following with no luck.
function GetDiPSWindow() {
var DiPSURL = "/DiPS/index";
var DiPSWindow = window.open("", "DiPS", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=520,height=875");
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
}
return DiPSWindow;
}
function AddRecipient(field, nameId) {
// Get window
var win = GetDiPSWindow();
// Attempt 1
$(win.document).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 2
$(win).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 3
$(win).load(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
}
Am I making a simple mistake?
EDIT For some reason, win.document.readyState is "complete". Not sure if that makes a difference.
I have also tried:
View contains:
<script>var CallbackFunction = function() {}; // Placeholder</script>
The method:
function AddRecipient(field, nameId) {
var DiPSURL = "/DiPS/index";
if (deliveryChannel === undefined) {
deliveryChannel = 0;
}
var DiPSWindow = GetDiPSWindow();
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
DiPSWindow.onload = function () { DiPSWindow.CallbackFunction = AddRecipient(field, nameId) }
} else {
var input = DiPSWindow.document.getElementById(field + "_Input");
input.value = input.value + nameId;
var event = new Event('change');
input.dispatchEvent(event);
}
}
The answer is.... kinda. it depends on what you are doing.
You can use jquery on the parent page to interact with a page within an iframe, however, anything that requires working with the iframe's document object may not work properly because jQuery keeps a reference of the document it was included on and uses it in various places, including when using document ready handlers. So, you can't bind to the document ready handler of the iframe, however you can bind other event handlers, and you can listen for the iframe's load event to know when it is absolutely safe to interact with it's document.
It would be easier though to just include jquery within the iframe itself and use it instead. It should be cached anyway, so there's no real detriment to performance by doing so.

Understanding module design patterns in javascript

I am trying to understand module patterns in Javascript so that i can separate my code into different modules and use them where required.
var messageHandler = (function(){
var el;
var display = function(a){
if(a=='error'){
el = $('.error');
el.css('display','block');
}
else if (a==='success'){
el = $('.success');
el.css('display','block');
}
else if (a=='warning'){
el = $('.warning');
el.css('display','block');
}
else if (a=='danger'){
el = $('.danger');
el.css('display','block');
}
registerClick(el.find('.close'));
return this;
}
function registerClick(p_el){
p_el.bind('click',function(){
hide();
});
}
var hide = function(){
el.css('display','none');
}
return {
display: display,
hide: hide
}
})();
window.messageHandler = messageHandler;
messageHandler.display('warning');
So, I have four different classes in css for different types of messages.The close class is for a small cross button on the top right to close the message.
This works fine till i call the function only once.When i do this
messageHandler.display('warning');
messageHandler.display('success');
Now both the messages close button have been bind to the success close button because el gets overwritten.
How to achieve it keeping the code reusable and concise.
The problem here is that you have a closure variable el that you are overwriting every time display() is called. The hide() function uses whatever is the current value of el at the time it is called, so overwriting el is a problem.
If you want to have "static" functionality like this display() method, you need to avoid shared state.
As #Bergi points out in the comments, you can eliminate the shared el and modify hide() to take an element as input:
var messageHandler = (function(){
var el; // delete this
var display = function(a){
var el; // add this
function registerClick(el){
el.bind('click', function(){
hide(p_el);
});
}
function hide(el){
el.css('display','none');
}
You could also modify hide to make use of the current event properties, and then just have:
function registerClick(el){
el.bind('click', hide);
}
function hide(event){
$(event.target).css('display','none');
}
Cleaned up version including the auto-hide discussed in the comments:
var messageHandler = (function(){
var display = function(a){
var el = $('.' + a);
el.css('display', 'block');
var hideAction = function () { el.css('display', 'block'); };
var token = setTimeout(hideAction, 5000);
el.find('.close').bind('click', function () {
hideAction();
clearTimeout(token);
});
return this;
}
return {
display: display
}
})();

How can I use variables only once with 'on mouseenter' and 'on mouseleave'?

I have multiple objects with different sizes that I want each to display additional box on mouseenter and hide on mouseleave. I have a jquery script that does it perfectly, my only concern is that I am repeating variables twice and something tells me that this can be done without repeating myself.
Problem is they both are strongly based on $(this) core element, so I can't make variables global. My guess was that I should put them withing the element container function, right before on mouseenter and on mouseleave are called, but syntax wise I have no idea how to do it. But again, I might be terribly wrong on that.
Here's the code:
$(document).ready(function() {
$('.box-options').hide();
var $boxModule = $('div.box');
$boxModule.on({
mouseenter: function() {
var $this = $(this), // repeat
$options = $this.find('div.options'), // repeat
$optionsBox = $this.find('div.options-box'); // repeat
var boxHeight = $this.height(), // repeat
boxWidth = $this.width(), // repeat
optionsBoxHeight = $optionsBox.outerHeight(); // repeat
if ( // statement referring to variables above }
else { // statement referring to variables above };
$options.fadeIn(200).addClass('shadow').css({"height" : boxHeight + optionsBoxHeight});
$optionsBox.delay(100).fadeIn(200).css({"top" : boxHeight}, 200);
},
mouseleave: function() {
var $this = $(this), // repeat
$options = $this.find('div.options'), // repeat
$optionsBox = $this.find('div.options-box'); // repeat
var boxHeight = $this.height(), // repeat
boxWidth = $this.width(), // repeat
optionsBoxHeight = $optionsBox.outerHeight(); // repeat
$optionsBox.hide().css({"top" : boxHeight});
$options.hide().removeClass('shadow').css({"height" : boxHeight}, 200);
}
});
});
Obviously the code contains more lines, but the important part is variables marked as // repeat. Does anyone know how I can re-structure the code to make variables be written only once?
UPDATE: I updated the code to describe logic better. Just to make it clear, on each page there are also multiple objects with identical classes, structure and size, only difference is content (text) within and id number.
Use hover function and for variables declare them before hovering event like you have done for $boxModule.
Calling
$( selector ).hover( handlerIn, handlerOut )
is shorthand for:
$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );
I think the solution for repetition in that code would be to create an external function to get some of the information from the element passed as an argument.
For example:
function options($element) {
return $element.find('div.options');
}
The same goes for every other property based on $(this).
Then you can just use your options inside your event handler as such: options($this).fadeIn(200)
Hope this helps to clean your code.
You can declare var outside on event like :
$('div.box').each(function(){
var $this = $(this),
$options = $this.find('div.options'),
$optionsBox = $this.find('div.options-box'),
boxHeight = $this.height();
$this.on({
mouseenter: function() {...}
mouseleave: function() {...}
});
});
How about making a function that return an object that you can use in every handler?
var calcVars = function(){
var $this = $(this),
$options = $this.find('div.options'),
$optionsBox = $this.find('div.options-box');
var boxHeight = $this.height(),
boxWidth = $this.width(),
optionsBoxHeight = $optionsBox.outerHeight();
return {
boxHeight: boxHeight,
//every other variable you need outside
}
$boxModule.on({
firstEvent: function() {
var object = calcVars.call(this);
object.calculatedProperty.doSomething();
//other code
},
secondEvent: function() {
var object = calcVars.call(this);
object.anotherCalculatedProperty.doSomething();
//other code
}
})
or you can do:
$boxModule.on("anEvent anotherEvent", function(event) {
/*
var declarations
*/
var $this = $(this),
//etc..
if(event.type == "anEvent"){
doStuff();
else if(event.type == "anotherEvent"){
doOtherStuff();
}
})

Copy/Paste element with jQuery

I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});

Can a JQuery plugin be called on a JQuery chain of methods or does it need to be called straight after a selector?

I'm having difficulty getting my textarea to expand vertically automatically.
I have some code to help make textarea auto expand vertically and for some reason it works when I clean out all my JS and provide a selector with reference to textarea e.g. $('textarea').autoGrow();
Calling the plugin on a chain of methods stops it from working. E.G.
micropostBox.hide().removeClass("micropost_content")
.addClass("micropost_content_expanded").show().autoGrow();
I established the plugin code works so copied all my working code to the same page and applied the autoGrow code to my textarea but it seems to be unresponsive. I noticed that the plugin I'm using the code from uses bind and unbind methods. In my code I use on and off methods from JQuery and wondering if this could be why the auto resizing of my textarea is not working?
Here is the code:
http://jsfiddle.net/erU5J/101/
autogrow plugin js code
$(function($) {
$.fn.autoGrow = function() {
return this.each(function() {
var txtArea = $(this);
var colsDefault = txtArea.attr('cols');
var rowsDefault = txtArea.attr('rows');
var updateSize = function() {
var linesCount = 0;
var lines = txtArea.attr('value').split('\n');
for (var i = lines.length - 1; i >= 0; --i) {
linesCount += Math.floor((lines[i].length / colsDefault) + 1);
}
if (linesCount >= rowsDefault) {
txtArea.attr('rows', linesCount + 1);
}
else {
txtArea.attr('rows', rowsDefault);
}
};
txtArea.unbind('.autoGrow').bind('keyup.autoGrow', updateSize).bind('keydown.autoGrow', updateSize).bind('change.autoGrow', updateSize);
});
};
});
my js code
$(function() {
$("div.microposts").on("focus", "textarea#micropostBox", function() {
var micropostForm = $(this).parent(),
micropostBox = micropostForm.find('textarea#micropostBox'),
micropostButton = micropostForm.find("input#micropostButton"),
xButton = micropostForm.find("div.xButton");
micropostBox.prop('rows', 7);
micropostForm.find('div#micropostOptions').removeClass('micropostExtraOptions');
micropostForm.find('div#postOptions').show();
$.trim(micropostBox.val()) == '' ? micropostButton.addClass("disabledMicropostButton").show()
:
micropostButton.prop('disabled', false);
micropostBox.hide().removeClass("micropost_content").addClass("micropost_content_expanded").show().autoGrow();
xButton.show();
micropostButton.prop('disabled', true);
micropostBox.off().on("keypress input change", function() {
micropostButton.prop({
disabled: !$.trim($(this).val()) != ''
});
$.trim($(this).val()) != '' ? micropostButton.removeClass("disabledMicropostButton").addClass("activeMicropostButton")
:
micropostButton.removeClass("activeMicropostButton").addClass("disabledMicropostButton");
});
xButton.on('click', function() {
micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
micropostForm.find('div#micropostOptions').addClass('micropostExtraOptions');
micropostBox.val("");
micropostForm.find('div#postOptions').hide();
xButton.hide();
micropostButton.hide();
micropostBox.removeAttr('style');
micropostBox.prop('rows', 0);
micropostForm.find('.imagePreview > img').remove();
micropostForm.find('.imagePreview').hide();
});
});
});
$(function() {
$('div.microposts').on('click', 'li#addImage', function() {
var form = $(this).parents('form#new_micropost'),
fileField = form.find('input#micropost_image');
fileField.trigger('click');
});
});
$(function() {
$('input#micropost_image').change(function(evt) { //.off() make sautoresize work
var image = evt.target.files[0],
form = $(this).parents('form#new_micropost'),
imagePreviewBox = form.find('div.imagePreview'),
reader = new FileReader();
reader.onload = function(evt) {
var resultdata = evt.target.result,
img = new Image();
img.src = evt.target.result;
imagePreviewBox.show().prepend(img);
};
reader.readAsDataURL(image);
});
});​
textarea
<textarea class="micropost_content" cols="40" id="micropostBox" name="micropost[content]" placeholder="" rows="0"></textarea>
It would be best to view a working example on jsfiddle. My aim is to have the auto resizing of textarea working before and after an image is added to the page using the image upload button in the textarea.
Kind regards
It depends if the method preceding the plugin call returned the jQuery object containing the elements to where the plugins need to be attached.
Here are a few examples of methods that do and do not return the elements you started with:
$('element') //get an element
.contents() //get an elements contents
.wrapAll('<div>') //wrapAll contents with div and returns the contents, not wrapper
.parent() //the wrapper
.parent() //the element
.myPlugin() //we attach a plugin to element
$('<div>')
.appendTo('body') //appendTo returns the same element, the div
.myPlugin() //attaches to the div
$('element') //get an element
.text() //get its text
.myPlugin() //chaining isn't possible since text() returns a string
Better read the docs for every method in jQuery and what it returns. Some DOM methods usually return the same element, some don't, and some don't return elements but values.
In summary, can plugins be attached after chains? YES, and it depends.
Refer to the jQuery's documentation
http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

Categories

Resources