I have the massive block of JS below. What steps can I take to clean it up as it the same function iterated for different div each time. Im throwing this out there as a general question as Im not sure what can be done to simplify code like this.
$(function() {
$('#1').hover(function() {
$('#1-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#1-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
$(function() {
$('#2').hover(function() {
$('#2-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#2-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
$(function() {
$('#3').hover(function() {
$('#3-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#3-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
$(function() {
$('#4').hover(function() {
$('#4-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#4-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
$(function() {
$('#5').hover(function() {
$('#5-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#5-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
$(function() {
$('#6').hover(function() {
$('#6-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#6-pin').find('.pin-bounce').removeClass('pin-hovered');
});
});
Assuming that the .pin-bounce is a child, you could create one hover function that works off of a common class and then inside of that just look for the class.
$('.some-common-class-instead-of-id').hover(function() {
$(this).find('.pin-bounce').addClass('pin-hovered');
}, function() {
$(this).find('.pin-bounce').removeClass('pin-hovered');
});
If it's not a child you could do something similar but instead of just finding children, you could build up a string like this:
$('.some-common-class-instead-of-id').hover(function() {
var idToFind = $(this).attr('id') + '-pin';
$('#' + idToFind).find('.pin-bounce').addClass('pin-hovered');
}, function() {
var idToFind = $(this).attr('id') + '-pin';
$('#' + idToFind).find('.pin-bounce').removeClass('pin-hovered');
});
You can use a for loop.
for (var i = 1; i <= 6; i++) {
(function(i){
$('#'+i).hover(function() {
$('#'+i+'-pin').find('.pin-bounce').addClass('pin-hovered');
}, function() {
$('#'+i+'-pin').find('.pin-bounce').removeClass('pin-hovered');
});
})(i);
}
Related
I wanted to make it as a loop for this ready function but I ended up doing like this:
$(document).ready(function () {
$('#p1-show').click(function () { $('#p1').show(); });
$('#p1-hide').click(function () { $('#p1').hide(); });
$('#p2-show').click(function () { $('#p2').show(); });
$('#p2-hide').click(function () { $('#p2').hide(); });
$('#p3-show').click(function () { $('#p3').show(); });
$('#p3-hide').click(function () { $('#p3').hide(); });
$('#p4-show').click(function () { $('#p4').show(); });
$('#p4-hide').click(function () { $('#p4').hide(); });
//there will be ids' for 300+ show hide
});
You can associate the element to be show() and hide() using custom data-* prefixed attribute, which can be retried using .data(key).
Using it you can use Class Selector to bind event handler.
HTML
<button class="show" data-target="#p1">show p1<button>
<button class="hide" data-target="#p1">hide p1<button>
Script
$(document).ready(function () {
$('.show').click(function () {
$(this).data('target').show();
});
$('.hide').click(function () {
$(this).data('target').hide();
});
})
$(document).ready(function () {
for(var i =1; i< 5; i++){
$(`#p${i}-show`).click(function () { $(`#p${i}`).show(); });
$(`#p${i}-hide`).click(function () { $(`#p${i}`).hide(); });
}
});
Don't use a loop. Use substring matching attribute selectors.
$("[id$=show]").on("click", function () {
$("#" + this.id.replace("-show", "")).show();
}):
$("[id$=hide]").on("click", function () {
$("#" + this.id.replace("-hide", "")).hide();
}):
try with this for loop it will help you
$(document).ready(function() {
for (var i = 0; i <= 300; i++) {
$('#p' + i + '-show').click(function() {
$('#p' + i).show();
});
$('#p' + i + '-hide').click(function() {
$('#p' + i).hide();
});
}
/* $('#p1-show').click(function () { $('#p1').show(); });
$('#p1-hide').click(function () { $('#p1').hide(); });
$('#p2-show').click(function () { $('#p2').show(); });
$('#p2-hide').click(function () { $('#p2').hide(); });
$('#p3-show').click(function () { $('#p3').show(); });
$('#p3-hide').click(function () { $('#p3').hide(); });
$('#p4-show').click(function () { $('#p4').show(); });
$('#p4-hide').click(function () { $('#p4').hide(); });
//there will be ids' for 300+*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Im trying to write a function that fades X elements out in sequence and once finished run another function.
function fadeOut(pro){
$('.interactive ul li').each(function(i) {
$(this).find('a').delay(200*(i+1)).fadeOut(200,function(){
$('.opening-title').delay(500).fadeOut();
});
showTimeline(pro);
});
}
function showTimeline(pro){
$('.timeline-container').addClass('in-view');
console.log(pro);
}
For some reason 'showTimeline()' runs at the same time and I can't understand why?
Full JS
$(document).ready(function() {
'use strict';
function init() {
function showPath(pro) {
fadeOut(pro);
}
function fadeOut(pro) {
$('.ul li').each(function(i) {
$(this).find('a').delay(1200 * (i + 1)).fadeOut(200, function() {
$('.title').delay(500).fadeOut();
});
});
showTimeline(pro);
}
function showTimeline(pro) {
$('.container').addClass('in-view');
console.log(pro);
}
$('.path').on('click', function() {
showPath( $(this).attr('data-pro') );
});
} //end init
init();
}); //end doc ready
You are calling showTimeline function in a loop. Call it this way instead ...
function fadeOut(pro) {
$('.interactive ul li').each(function(i) {
$(this).find('a').delay(200 * (i + 1)).fadeOut(200, function() {
$('.opening-title').delay(500).fadeOut();
});
});
showTimeline(pro);
}
function showTimeline(pro) {
$('.timeline-container').addClass('in-view');
console.log(pro);
}
You need to wait until all elements are faded. Working Example
But, basically just add a counter to know when all elements are faded:
var hiddenElements = 0;
function fadeOut(pro){
$('.interactive ul li').each(function(i) {
$(this).find('a').delay(200*(i+1)).fadeOut(200,function(){
$('.opening-title').delay(500).fadeOut();
hiddenElements++;
if (hiddenElements === $('.interactive ul li').length){
showTimeline(pro);
}
});
});
}
You can use jquery when
Hope this snippet will be useful
var fadeOut=function(pro){
$('.interactive ul li').each(function(i) {
$(this).find('a').delay(200*(i+1)).fadeOut(200,function(){
$('.opening-title').delay(500).fadeOut();
});
showTimeline(pro);
});
}
var showTimeline=function(pro){
$('.timeline-container').addClass('in-view');
console.log(pro);
}
$.when(fadeOut()).then(showTimeline());
I am not able to completely test it but you can try this
$(document).ready(function() {
'use strict';
$('.path').on('click', function() {
$.when(fadeOut($(this).attr('data-pro'))).then(showTimeline($(this).attr('data-pro')));
});
function fadeOut(pro) {
$('.ul li').each(function(i) {
$(this).find('a').delay(1200 * (i + 1)).fadeOut(200, function() {
$('.title').delay(500).fadeOut();
});
});
}
function showTimeline(pro) {
$('.container').addClass('in-view');
console.log(pro);
}
});
Here's my relevant code:
var dropdown = {
init: function() {
$(".dropdown").click(".dropdown", dropdown.openDropdown, dropdown.secondFunction);
},
openDropdown: function() {
...
}
}
How can I call multiple functions on the click event? I added what I tried to do above.
EDIT:
So this is my new code with your guys help, and I can confirm both functions are being called because when I put alerts in they both trigger, but for some reason the code inside openDropdown right now isn't working. Is it because my $(this) references are off or something?
var dropdown = {
init: function() {
$(".dropdown").click(".dropdown", function() { dropdown.openDropdown(); dropdown.closeDropdowns(); });
},
openDropdown: function() {
$(this).children(".dropdown-menu").show();
$(this).addClass("open");
},
closeDropdowns: function() {
//$(".open").removeClass(".open");
//$(".open").children(".dropdown-menu").hide();
}
}
like this:
var dropdown = {
init: function() {
$(".dropdown").click(".dropdown", function(){ this.openDropdown(); this.secondFunction()});
},
openDropdown: function() {
...
}
}
You can do:
$('.dropdown').on('click', function () {
dropdown.openDropdown();
dropdown.secondFunction();
});
If you want this inside of openDropdown and secondFunction to be the element you would need to use .call.
var dropdown = {
init: function() {
$(".dropdown").on("click", function () {
// The call makes `this` the element in the functions...
dropdown.openDropdown.call(this);
dropdown.secondFunction.call(this);
});
},
openDropdown: function() {
console.log('openDropdown', this);
},
secondFunction: function() {
console.log('secondFunction', this);
}
};
dropdown.init();
var dropdown = {
init: function() {
$(".dropdown").click(".dropdown", function() {dropdown.openDropdown(); dropdown.secondFunction();
});
},
openDropdown: function() {
// first function callback
},
secondFunction: function() {
// second call back
}
};
dropdown.init();
DEMO
I know my way around several programming languages but am struggling understanding Javascript and how it's used in mobile apps. I'm developing for BlackBerry and a using the BlackBerry 10 jQuery Mobile Theme. I'm looking at the App.js from the samples and am confused as to what the App object is.
App = {};
App.init = function () {
console.log("App Init");
App.utils.metaHack();
$("#activity").live("pageinit", function(){
App.page.activity.init();
});
$("#bb_activity").live("pageinit", function(){
App.page.bb_activity.init();
});
$("#progressPage").live("pageinit", function(){
App.page.progress.init();
});
$("#sliderPage, #sliderPageDark").live("pageinit", function(){
App.page.slider.init();
});
$("#togglePage, #togglePageDark").live("pageinit", function(){
App.page.toggle.init();
});
$("#actionBarSample").live("pageinit", function() {
App.page.actionBarSample.init();
});
$('#applicationMenu').live("pageinit", function() {
App.page.applicationMenu.init();
});
}
App.utils = {
metaHack: function () {
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
}
}
App.page = {
activity: {},
bb_activity: {},
progress: {},
slider: {},
toggle: {},
actionBarSample: {},
applicationMenu: {}
}
App.page.activity.init = function() {
$('#show').on('click', function () {
$.mobile.loading('show');
});
$('#text').on('click', function() {
$.mobile.loading('show', {
text: 'Loading',
textVisible: true,
textonly: true,
theme: 'a'
});
});
$('#swatch-a').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'a'
});
});
$('#swatch-a-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'a'
});
});
$('#swatch-c').on('click', function() {
$.mobile.loading( 'show', {
text: 'Loading',
textVisible: true,
theme: 'c'
});
});
$('#swatch-c-notext').on('click', function() {
$.mobile.loading( 'show', {
theme: 'c'
});
});
$('#hide').on('click', function () {
$.mobile.loading('hide');
});
}
App.page.bb_activity.init = function() {
console.log("bb_activity");
$('#throttle').on('change', function () {
console.log("throttle");
var speed = $('#throttle').val();
$('#speedTest').activityindicator('speed', speed+'s');
});
}
App.page.progress.init = function() {
var p = 0;
var error = pause = false;
function watchProgress() {
if( p > 100 || error || pause) {
return;
}
$('#rogress').progressbar("setValue", p);
p+= 4;
setTimeout(watchProgress, 100);
}
$('#start').on('vclick', function () {
error = false;
watchProgress();
});
$('#error').on('vclick', function () {
$('#rogress').progressbar("setError", error = !error);
});
$('#pause').on('vclick', function () {
$('#rogress').progressbar("pause", pause = !pause);
});
$('#reset').on('vclick', function () {
p = 0;
error = pause = false;
$('#rogress').progressbar("setValue", p);
});
}
App.page.slider.init = function() {
$('#slider-disabled').slider('disable');
$('#slider-disabled-highlight').slider('disable');
}
App.page.toggle.init = function() {
console.log("toggle init");
$('#flip-disabled').slider('disable');
}
App.page.actionBarSample.init = function() {
var $tabo = $("#tover"),
overflowState = $tabo.hasClass("noContent");
$("#left").on("panelbeforeopen", function() {
//Save the state of the overflow button
overflowState = $tabo.hasClass("noContent");
$tabo.addClass("noContent");
})
.on("panelbeforeclose", function() {
//Put the overflow button into the correct state
if(!overflowState) {
$tabo.removeClass("noContent");
}
});
//Handle overflow menu clicks
$(".bb10-panel").bind("vclick", function() {
//Close the panel
$(this).panel("close");
});
$("#left li").bind("vclick", function() {
//Clear the active state from any other buttons that may have been set to active
$(this).siblings().removeClass("ui-btn-active");
//Add the active state to the selected button
$(this).addClass("ui-btn-active");
//Clear the contents of the tab overflow button
//Add class to put the tab overflow icon in the correct position
//Clear the active state from all tab buttons in action bar
$('[data-role="tab"], [data-role="tab-overflow"]').removeClass("active");
});
$(".inBar").bind("vclick", function() {
//Set the active state to the tab in the actionbar
$('#' + this.id.slice(0, 2)).addClass("active");
$tabo.addClass("noContent").empty();
overflowState = true;
});
$(".notInBar").bind("vclick", function() {
//Set the active state to the tab overflow button
$tabo.empty()
.addClass("active")
.html('<img src="img/generic_81_81_placeholder.png" alt=""><p>' + $(this).text() + '</p>')
.removeClass("noContent");
overflowState = false;
});
$("[data-role='tab']").bind("vclick", function() {
//Change page on tab click
if($(this).data("href")) {
$.mobile.changePage( $(this).data("href"), { transition: "slideup"} );
}
});
}
App.page.applicationMenu.init = function() {
if(typeof blackberry != 'undefined'){
blackberry.event.addEventListener('swipedown', function(){
$('#top').panel("open");
});
$('#menuBtn').css('display','none');
}
else{
$('#simulInst').css('display','none');
}
}
App.init();
Is App an object specific to Blackberry? I did some dabbling and made a small app but didn't use App or init anything.
App in this example is defined at the top:
App = {};
So it's just a new plain old JavaScript object (dictionary), which they then define functions and data to it e.g. App.utils = ....
You can try it out on a browser, press F12 and then go to the console (ESC) and type e.g. blah = {} and you will see a new object created with the name blah. Everything is an object in JavaScript apparently.
Read more
http://www.w3schools.com/js/js_objects.asp
Setting the Selector's:
btNext = $('<a>' + options.labelNext + '</a>').attr("href", "#").addClass("buttonNext");
btPrevious = $('<a>' + options.labelPrevious + '</a>').attr("href", "#").addClass("buttonPrevious");
btFinish = $('<a>' + options.labelFinish + '</a>').attr("href", "#").addClass("buttonFinish");
test = $('<a class="LinkMe" href="#">MotherBoard</a>')
Click():
$(test).click(function () {
showStep(0);
});
$(btNext).click(function () {
if ($(this).hasClass('buttonDisabled')) {
return false;
}
doForwardProgress();
if ($.isFunction(options.onNext)) {
if (!options.onNext.call(this, $(steps))) {
}
}
return false;
});
$(btPrevious).click(function () {
if ($(this).hasClass('buttonDisabled')) {
return false;
}
doBackwardProgress();
if ($.isFunction(options.onPrevious)) {
if (!options.onPrevious.call(this, $(steps))) {
}
}
return false;
});
$(btFinish).click(function () {
if (!$(this).hasClass('buttonDisabled')) {
if ($.isFunction(options.onFinish)) {
if (!options.onFinish.call(this, $(steps))) {
return false;
}
} else {
var frm = obj.parents('form');
if (frm && frm.length) {
frm.submit();
}
}
}
return false;
});
ALL of the click functions work EXCEPT the selector (test), ive tried taking the click function out of the plugin and in a
$(document).ready(function () {});
and it still doesnt work thier, Please help.
Try doing:
test.click(function() {});
or
$("a.LinkMe").click(function() {});
// since test is a link having a class 'LinkMe'
But if those elements are dynamically added into your HTML, you can use .on() or .delegate()
$("a.LinkMe").on("click", function() {});
// OR
$(document).on("click", "a.LinkMe", function() {});
// OR
$("body").delegate("a.LinkMe", "click", function() {});
Take a look at this.
Instead of doing
test = $('<a class="LinkMe" href="#">MotherBoard</a>')
You'll want to do instead
$test = $('a.LinkMe');
// or just
$test = $('.LinkMe');
Same for the btNext, btPrevious, btFinish. I'm not sure why they work, maybe someone else can explain it to me.