Accordion Next Button - javascript

I have tried searching for what I am trying to accomplish, however I have not found what I am looking for.
I am looking to create a Next and Previous button inside the content of the Spry Accordion provided with Dreamweaver CS6. I have searched the SpryAccordion.js and found this code below:
Spry.Widget.Accordion.prototype.openNextPanel = function()
{
return this.openPanel(this.getCurrentPanelIndex() + 1);
};
Spry.Widget.Accordion.prototype.openPreviousPanel = function()
{
return this.openPanel(this.getCurrentPanelIndex() - 1);
};
So I attempted to do this with "#acc-step-1-next" being my "Next" button in Panel 1.
<script>
$(document).ready(function(){
$("#acc-step-1-next").click(function(){
Spry.Widget.Accordion.prototype.openNextPanel = function(){
return ('#Accordian1').openPanel(this.getCurrentPanelIndex() + 1);
};
});
});
</script>
I was wondering if doing it this way might make it easy! How would I go about applying this? Would this work or not?
Also, with the "Next" button, could I just make it ".acc-step-next" and use it universally, instead of individually assigning new ID's?
EDIT:
Sorry, yes I read your answer incorrectly. I have tried searching for the init property, however have had no success.
This is what starts in the Accordion JS file:
(function() { // BeginSpryComponent
if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.Accordion = function(element, opts)
{
this.element = this.getElement(element);
this.defaultPanel = 0;
this.hoverClass = "AccordionPanelTabHover";
this.openClass = "AccordionPanelOpen";
this.closedClass = "AccordionPanelClosed";
this.focusedClass = "AccordionFocused";
this.enableAnimation = true;
this.enableKeyboardNavigation = true;
this.currentPanel = null;
this.animator = null;
this.hasFocus = null;
this.previousPanelKeyCode = Spry.Widget.Accordion.KEY_UP;
this.nextPanelKeyCode = Spry.Widget.Accordion.KEY_DOWN;
this.useFixedPanelHeights = false;
this.fixedPanelHeight = 0;
Spry.Widget.Accordion.setOptions(this, opts, true);
if (this.element)
this.attachBehaviors();
};
Which I added this after, but still no luck:
var acc_next = document.getElementById("acc-step-next");
var acc_prev = document.getElementById("acc-step-prev");
$("acc_next").click(function(){
accordion.openNextPanel();
});
$("acc_prev").click(function() {
accordion.openPreviousPanel();
});

I have never worked with Spry.Widget.Accordion, but I would try something like the following.
Search for the code, where your accordion is initialized, it should look something like that:
var accordion = new Spry.Widget.Accordion("Accordian1",{});
And add this just below:
$(".acc-step-next").click(function(){
accordion.openNextPanel();
});
Together it could look something like that:
<script type="text/javascript">
$(document).ready(function(){
var accordion = new Spry.Widget.Accordion("Accordian1",{});
// Add a click handler to all buttons with the class 'acc-step-next' (yes you can do that)
$(".acc-step-next").click(function(){
// when the button is clicked, call the openNextPanel method of the accordion instance we saved above
accordion.openNextPanel();
});
});
</script>

Related

Javascript: managing clicks from one instance to the next

I am very new to Javascript.
I am trying to write this baby jQuery plugin that I will use to make dropdown lists. What I am failing to achieve (beyond things that I do not notice) is to neatly exit or deactivate my active instance as I click on another instance. I tried to illustrate my problem in the following fiddle (keeping the structure I am using):
https://jsfiddle.net/andinse/m0kwfj9d/23/
What the Javascript looks like:
$(document).ready(function() {
$.fn.activator = function() {
var Activator = function(el) {
this.html = $('html');
this.el = el;
this.is_active = false;
this.initialize();
};
Activator.prototype.initialize = function() {
var self = this;
self.el.on('click', function(e) {
if (self.is_active === false) {
self.toggle('activate');
} else {
self.toggle('deactivate');
}
});
};
Activator.prototype.toggle = function(action) {
var self = this;
if (action === 'activate') {
console.log('activating ' + self.el[0].className);
self.is_active = true;
self.el.addClass('red');
self.html.on('click', function(e) {
if (e.target != self.el[0]) {
self.toggle('deactivate');
}
});
}
if (action === 'deactivate') {
console.log('deactivating ' + self.el[0].className);
self.is_active = false;
self.el.removeClass('red');
self.html.off('click');
}
};
if (typeof this !== 'undefined') {
var activator = new Activator(this);
}
return this;
};
$('.a').activator();
$('.b').activator();
$('.c').activator();
});
My idea was:
To watch for clicks on html as soon as the instance is active (thus ready to be deactivated). On click, to check if the event.target is the same as the active instance. If not, to deactivate this instance.
To stop watching for clicks as soon as the instance is inactive. So that we're not doing unnecessary work.
When it is set like this, it seems to work for only one cycle (click on A activates A then click on B activates B and deactivates A then click on C activates C but doesn't deactivate B).
If I get rid of the "self.html.off('click')" it seems to work kind of ok but if I look at the log I can see the "toggle" function is sometimes triggered multiple times per click. There must be a cleaner way.
Any piece of help greatly appreciated.
With your logic, when clicking any element you should deactivate any current activated element. Either do it globally:
$('.your_activation_class').removeClass('.your_activation_class');
or in some parent scope
$('some_parent_selector .your_activation_class').removeClass('.your_activation_class');

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 optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
$(document).ready(function () {
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
var $fundosdiponiveis = $('#fundosdiponiveis');
var $fundosdiponiveisTab = $('#tabs1');
$defensivo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$defensivoSubTab.removeClass("hide");
$defensivoSubTab.show();
});
$equilibrado.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$equilibradoSubTab.removeClass("hide");
$equilibradoSubTab.show();
});
$activo.live('click', function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
$activoSubTab.removeClass("hide");
$activoSubTab.show();
});
});
</script>
For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');
This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');
That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');
And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');
Any suggestion?
You could write a function that returns the proper function:
function createShowTabFunc(tab) {
return function () {
$fundosdiponiveis.removeClass("subshow show").addClass("hide");
tab.removeClass("hide");
tab.show();
}
}
Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));
Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

trying to remove and store and object with detach()

I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Categories

Resources