Recently I am giving another shot to Dashcode ;)
It's great. Is just I think is not well documented.
I have a stackLayout object with only two views in it, and a couple of buttons that interchange the views with a transition.(views show data of a large array, list)
Animations and transitions work perfect. The problem is, when I press a button while animating the animation starts again and it looks ugly (If I had n views for a datasource array of length n this should't be a problem, but this is not my case).
I want to disable buttons while animation is taking place.
Is there any callback, delegate, or any way I can get a notification when the animation is finished?
This is what I have done:
function _changeView(transitionDirection, newIndex){
//Create transition
var newTransition = new Transition(Transition.SWAP_TYPE, 0.9, Transition.EASE_TIMING);
newTransition.direction = transitionDirection;
//I only have two views. I use currentView's id to calculate not current view id and change text inside of it.
var stackLayout = document.getElementById('stackLayout').object;//stackLayout object
var nextViewId = (stackLayout.getCurrentView().id == 'view1')? '2':'1'; //
//change the text in the view that is going to appear
document.getElementById('text'+nextViewId).innerHTML = list[curIndex];
stackLayout.setCurrentViewWithTransition('view'+ nextViewId, newTransition, false);
}
function goPrevious(event)
{
curIndex--;
if(curIndex < 0){
curIndex = list.length-1;
}
_changeView(Transition.LEFT_TO_RIGHT_DIRECTION, curIndex);
}
function goNext(event)
{
curIndex++;
if(curIndex >list.length - 1){
curIndex = 0;
}
_changeView(Transition.RIGHT_TO_LEFT_DIRECTION, curIndex);
}
Eventually found the answer to this. Here's how I did it:
document.getElementById('stackLayout').object.endTransitionCallback=function(stackLayout, oldView, newView) {
//PUT CODE HERE USING stackLayout, oldView, newView to show params
}
In fact you can find all the stackLayout methods and properties in the StackLayout.js file in your project!!
Hope this helps
Related
I am using this function below to find the data value inside of 3 possible DIVs. The data attribute dynamically changes each time that a slide changes position. I am trying to get the correct returned value of false, but it incorrectly returns true for each slide. What might be the problem?
$('.slidelink').on('click', function(e) {
var parent = $(this).parent().parent().parent().parent();
var parent_name = parent[0].nodeName.toLowerCase();
var parent_tagname = $(parent_name);
if (parent_tagname.attr('data-isactiveslide') == 'true') {
alert('working!');
}
});
And the HTML, which represent individual slides in Revolution Slider Wordpress plugin:
<rs-slides>
<rs-slide data-isactiveslide="false">
<rs-layer-wrap>
<rs-loop-wrap>
<rs-mask-wrap>
<rs-layer class="slidelink"></rs-layer>
</rs-mask-wrap>
</rs-loop-wrap>
</rs-layer-wrap>
</rs-slide>
</rs-slides>
You are walking up the tree referencing the element name. Using that to find all the elements in the page with that tag, and looking at the first one.
$('.slidelink').on('click', function(e) {
var parent = $(this).closest("[data-isactiveslide]");
console.log(parent.data('isactiveslide'))
});
I haven't been able to find my specific case on here yet so I thought I'd ask. I'm trying to make a very simple Tamagotchi in Javascript for a school project. Musts are that I apply DOM manipulation, use a loop, use an array(or an object), and use a function.
My idea was to make an array with all the 'emotions' as images and then a for loop to slowly count them down. Giving the impression that the mood of the Tamagotchi gets worse as time passes.
This is the code I have so far, it's not a lot:
var imgArray = ["super.png", "blij.png", "neutraal.png", "meh.png", "verdrietig.png", "dood.png"] //Array with the images
for (var i = 0; i < imgArray.length; i++)
{
//for loop that counts down array
//Here I want a function that changes the image according to the array number
}
Sorry for the bad formatting, this is my first time on here :)
This is what I have in the body:
<h1>Tamagotchi</h1>
<button id="feed">Give food</button>
<button id="play">Entertain</button>
<button id="walk">Walk</button>
<div id="tamagotchi"></div>
I'd also then like the buttons that you see above to add points to make the Tamagotchi feel better (so in the for loop the array automatically keeps ++i but I'd like the button to --i, so subtract one point) imgArray[0] is the happiest and imageArray[5] is the saddest.
I hope this wasn't too vague, please let me know if I need to better explain anything!
Here is some draft so you can start from something. I've created a function allowing you to improve the state of the tamagoshi.
For you now :
Making a function to decrease it
Make them to be displayed as image and not strings
Make it prettier using css rules
If you get trouble with the code, Stack Overflow will help. SO is not made to write code from scratch, but to fix bug and coding issues.
// Array with the images
const imgArray = [
'super.png',
'blij.png',
'neutraal.png',
'meh.png',
'verdrietig.png',
'dood.png',
];
let tamagoshiState;
// Pointer to the div where you are going to insert the picture
const tamagoshiFeel = document.getElementById('tamagotchi');
// Function that can change the state of the tamagoshi
function setTamagoshiState(i) {
tamagoshiState = i;
tamagoshiFeel.innerHTML = imgArray[i];
}
// Change the tamagoshi state in a positive way
function improveTamagoshiState() {
// Tamagoshi can't be happier
if (tamagoshiState === 0) {
return;
}
setTamagoshiState(tamagoshiState - 1);
}
// Initialize the tamagoshi state at very sad
setTamagoshiState(imgArray.length - 1);
#tamagotchi {
margin-top: 2em;
}
<h1>Tamagotchi</h1>
<button id="feed" onclick="improveTamagoshiState()">Give food</button>
<button id="play" onclick="improveTamagoshiState()">Entertain</button>
<button id="walk" onclick="improveTamagoshiState()">Walk</button>
<!-- How the tamagochi feels -->
<div id="tamagotchi">
</div>
So I have a photo gallery on my front page that switches between two images; each image links to a different page. Now, beside that gallery I have two links that go to the same two pages. The idea is that when image A is showing, side-link A should be highlighted with a border. The issue I keep running into is that once I get either side-link to be highlighted, I don't really know how to get it unhighlighted. Instead of switching with the images, they just stay highlighted.
var debugLink = "#firstLink";
function displayNextImage()
{
index++;
if(index >= indexgalpics.length)
{
index=0;
}
//---this is where I set the var debugLink which is
// supposed to carry the selected linke
if(index == 0)
{
console.log("first link selected");
//---when image A is showing, top side-link should be highlighted
//---ok so we know this much works, it seems these double equal
// signs are very important here.
//---makeActive();
//---but once makeActive() is called here, it makes the first link
// active for the entire time.
//---we can't put the entire style code here because same as before,
// it just keeps the link highlighted forever
debugLink = "#firstLink";
//---ok so i can set a var at top to a value in the makeActive() function,
// but i think the way JS works highlights either one forever
debugLink = "#firstLink";
}
else if(index == 1)
{
console.log("second link should be selected");
//---when image B is showing, bottom side-link should be highlighted
debugLink = "#secondLink";
}
showImg();
}
function makeActive()
{
var activeLink = document.querySelector(debugLink);
//---adds style to the debugLink
}
The function makeActive() is called in the function showImg(), and the function displayNextImage() is called in another function that sets the timer.
I changed your approach a little bit by using a boolean for the index, because you seem to only need two states.
Here is a revised version:
Note: In this code, I've used custom-made functions to make the code easier to read. I created hasClass(el,class), addClass(el,class), removeClass(el,class), toggleClass(el,class,bool). You can find them in the final JS Fiddle.
// Register the link elements
var links = {
true : document.getElementById('firstLink'),
false : document.getElementById('secondLink')
},
// Keep track of selected link (replaces your 'index')
leftLinkActive = false,
// Just so you don't go get it every time
gallery = document.getElementById('gallery');
// Let's trigger the gallery
displayNextImage();
// We'll change the active link and show the correct image
function displayNextImage(){
leftLinkActive = !leftLinkActive;
if(leftLinkActive){ console.log("first link selected"); }
else{ console.log("second link selected"); }
makeActive();
showImg();
// Let's do that again in 2 seconds
setTimeout(displayNextImage,2000);
}
// Add / remove the active class
function makeActive(){
addClass( links[ leftLinkActive ], 'active-class');
removeClass( links[ !leftLinkActive ], 'active-class');
}
// Change the image with a small fadeOut transition
function showImg(){
addClass(gallery,'fadeOut');
setTimeout(function(){
// Here we switch from img1 and img2
gallery.style.backgroundImage = 'url('+(leftLinkActive?'im1.jpg':'im2.jpg')+')';
removeClass(gallery,'fadeOut');
},200);
}
JS Fiddle Demo
This is the sequel to this thread:
4 toggle buttons speak javascript to each other but none of them are good listeners
Our heros have overcome the ridiculous amount of nonsense originally presented in the fiddle http://jsfiddle.net/EjW7A/8/ (no longer available) when #nbrooks -reinvigorated by the forces of good- conquered all of the stupidly placed arrays, functions and the mammoth amount of redundant content with his solution:
http://jsfiddle.net/EjW7A/24/
We rejoin Luhring after 8 hours of poking, prodding, red bull drinking, concrete wall head-bashing at the final step of solving the epic problem of doom- implementation:
The new fiddle:
http://jsfiddle.net/Luhring/EjW7A/38/
Problem:
How can I insert the content dynamically- allowing each button to toggle it's own content while making sure the other buttons are toggled off and their content hidden? ex, if button 1 is toggled on (it is animated as if it were a 'real' pressed button), button 1s content is displayed in a gallery where the contents can be clicked to display a lightbox. when button 2 is clicked should toggle button 1 off and replace button 1's contents with its own.
New Working Demo
Anything invoking jQuery on DOM elements must be wrapped within the DOM ready function to work correctly (this is why your $('a').click() was failing. Also, normally if you see yourself creating multiple arrays that you never end up using, and still end up referencing each element directly, you're making a lot of wasted effort. I cleaned your code up a bit - take a look:
jQuery(document).ready(function($) {
//variable declaration section.
var contentArray = ['albumArt', 'logoDesign', 'UX', 'other'],
content = {}, newClassName, $selectedArray, i;
for ( i = 0; i < contentArray.length; i++) {
var className = contentArray[i];
content[className] = $('.' + className);
}
//prevent links that are clicked from going anywhere
$("a").click(function(e) {
e.preventDefault();
});
$('.workTypes').click(function() {
if ($(this).is('#centeringDiv a')) return;
$(this).toggleClass('workTypesSelected');
$('.workTypesSelected').not(this).removeClass('workTypesSelected');
$selectedArray = content[$('.workTypesSelected').attr('id')];
$('#galleryDiv').empty();
if ( $selectedArray ) {
// note creates #largeGallery elements dynamically
for ( i = 0; i < $selectedArray.length; i++ ) {
var $selected = $selectedArray.eq(i);
$('<a>').attr({
href: $selected.attr('href'),
title: $selected.attr('title'),
class: "lb_gal"
}).append(
$('<img>').attr({
id: "largeGallery"+i,
src: $selected.attr('href'),
class: "gallery cf"
}).rlightbox()
)
.appendTo('#galleryDiv')
.rlightbox();
}
}
}); // end click handler
}); //end the document ready jquery function​
I am using Safalra's javascript to create a collapsible list. The script works across several browsers with no problem. However, when I apply the javascript to my own list, it fails to act as expected when I use IE (I'm using 7 at the moment). It simply writes the list, without the expand and contract images.
I copied the Safalra's javascript precisely, so I assume the error must be in my own list. This is how I generated my list:
<body onLoad="makeCollapsible(document.getElementById('libguides'));">
<ul id="libguides">
<script type="text/javascript" src="http://api.libguides.com/api_subjects.php?iid=54&more=false&format=js&guides=true&break=li"></script>
</ul>
(Yes, I do close the body tag eventually.) When I run this in IE, it tells me that line 48 is causing the problem, which appears to be:
node.onclick=createToggleFunction(node,list);
Here's the entire function:
function makeCollapsible(listElement){
// removed list item bullets and the sapce they occupy
listElement.style.listStyle='none';
listElement.style.marginLeft='0';
listElement.style.paddingLeft='0';
// loop over all child elements of the list
var child=listElement.firstChild;
while (child!=null){
// only process li elements (and not text elements)
if (child.nodeType==1){
// build a list of child ol and ul elements and hide them
var list=new Array();
var grandchild=child.firstChild;
while (grandchild!=null){
if (grandchild.tagName=='OL' || grandchild.tagName=='UL'){
grandchild.style.display='none';
list.push(grandchild);
}
grandchild=grandchild.nextSibling;
}
// add toggle buttons
var node=document.createElement('img');
node.setAttribute('src',CLOSED_IMAGE);
node.setAttribute('class','collapsibleClosed');
node.onclick=createToggleFunction(node,list);
child.insertBefore(node,child.firstChild);
}
I confess I'm too much of a javascript novice to understand why that particular line of code is causing the error. I looked at some of the other questions here, and was wondering if it might be a problem with setAttribute?
Thanks in advance.
Edited to add:
Here's the code for the createToggleFunction function. The whole of the script is just these two functions (plus declaring variables for the images).
function createToggleFunction(toggleElement,sublistElements){
return function(){
// toggle status of toggle gadget
if (toggleElement.getAttribute('class')=='collapsibleClosed'){
toggleElement.setAttribute('class','collapsibleOpen');
toggleElement.setAttribute('src',OPEN_IMAGE);
}else{
toggleElement.setAttribute('class','collapsibleClosed');
toggleElement.setAttribute('src',CLOSED_IMAGE);
}
// toggle display of sublists
for (var i=0;i<sublistElements.length;i++){
sublistElements[i].style.display=
(sublistElements[i].style.display=='block')?'none':'block';
}
}
}
Edited to add (again):
Per David's suggestion, I changed all instances of setAttribute & getAttribute...but clearly I did something wrong. IE is breaking at the 1st line (which is simply the doctype declaration) and at line 49, which is the same line of code where it was breaking before:
node.onclick=createToggleFunction(node,list);
Here's the first function as written now:
function makeCollapsible(listElement){
// removed list item bullets and the sapce they occupy
listElement.style.listStyle='none';
listElement.style.marginLeft='0';
listElement.style.paddingLeft='0';
// loop over all child elements of the list
var child=listElement.firstChild;
while (child!=null){
// only process li elements (and not text elements)
if (child.nodeType==1){
// build a list of child ol and ul elements and hide them
var list=new Array();
var grandchild=child.firstChild;
while (grandchild!=null){
if (grandchild.tagName=='OL' || grandchild.tagName=='UL'){
grandchild.style.display='none';
list.push(grandchild);
}
grandchild=grandchild.nextSibling;
}
// add toggle buttons
var node=document.createElement('img');
node.src = CLOSED_IMAGE;
node.className = 'collapsibleClosed';
node.onclick=createToggleFunction(node,list);
child.insertBefore(node,child.firstChild);
}
child=child.nextSibling;
}
}
And here's the second function:
function createToggleFunction(toggleElement,sublistElements){
return function(){
// toggle status of toggle gadget
// Use foo.className = 'bar'; instead of foo.setAttribute('class', 'bar');
if (toggleElement.className == 'collapsibleClosed') {
toggleElement.className = 'collapsibleOpen';
toggleElement.src = OPEN_IMAGE;
} else {
toggleElement.className = 'collapsibleClosed';
toggleElement.src = CLOSED_IMAGE;
}
// toggle display of sublists
for (var i=0;i<sublistElements.length;i++){
sublistElements[i].style.display=
(sublistElements[i].style.display=='block')?'none':'block';
}
}
}
Internet Explorer (until version 8, and then only in best standards mode) has a very broken implementation of setAttribute and getAttribute.
It effectively looks something like this:
function setAttribute(attribute, value) {
this[attribute] = value;
function getAttribute(attribute, value) {
return this[attribute];
}
This works fine iif the attribute name matches the property name, and the property takes a string value.
This isn't the case for the class attribute, where the matching property is className.
Use foo.className = 'bar'; instead of foo.setAttribute('class', 'bar');
node.onclick=createToggleFunction(node,list);
That is probably not what you want. Does createToggleFunction return a function? If it doesn't, then I bet you meant this:
node.onClick = function() { createToggleFunction(node, list); };
If my guess is right then the way you have it will set the onClick event handler to be the result of createToggleFunction, not a function like it needs to be.