Variables within function is null - javascript

I have the following function:
function slideDown() {
//get the element to slide
sliding = document.getElementById('slideDiv1');
//add 1px to the height each time
sliding.style.height = parseInt(sliding.style.height)+1+'px';
t = setTimeout(slideDown,30);
if (sliding.style.height == "401px") {
clearTimeout(t);
}
}
which is called within this function:
function addDiv(nextImageSlide) {
//finds the src attribute of the image nested in the Li
elemChild = nextImageSlide.firstChild;
imageSrc = elemChild.getAttribute('src');
//loops and creates six divs which will be the slices. adds background property etc
for (i = 0, j = 0, k = 1; i< = 19; i++, j++, k++) {
var newDiv = document.createElement('div');
newDiv.setAttribute('class', 'new-div');
newDiv.id='slideDiv' + k;
newDiv.style.height = '1px';
newDiv.style.background = 'url(' + imageSrc +') scroll no-repeat - '+39.5 * j + 'px 0';
var a = document.getElementById('content');
a.appendChild(newDiv);
}
slideDown();
}
Which is called within another function that defines nextImageSlide. It later removes all the divs that it just made.
The idea is for an image gallery. When the user hits the next button, I want slices of the next image to slide down to show the next image. Those slices are then taken away and the new image revealed.
I would like something like this: http://workshop.rs/projects/jqfancytransitions/.
It's for an assignment so we have to write all the code ourself and this is the best way I can think to replicate it. The only problem is that I keep getting an error:
'sliding is null. sliding.style.height = parseInt(sliding.style.height)+1+'px';'
No matter what I do I can't get rid of it. The thing is if I define sliding as a totally different id, (for example I made a random little div outside of everything), it working.
This error shows when I try to access the divs, it just made that it throws a hissy fit.
Anyone see any errors in my code?

Hopefully this is just a typo while pasting into the site here, but:
car a = document.getElementById('content');
^---syntax error, which'll kill your entire script - var?

Related

How can I put off everything in my code until a button is clicked?

Working on a JavaScript program, and the first thing that happens when run is asking the user whether they want to enter something using prompt()s, or using a textarea. The textarea option comes with a clickable button element to press once the user has entered everything they want into the textarea.
If this option is chosen, I want the rest of my program to not run until this button is clicked, and the user is confirming that they are finished with their input. Currently I have the button code within the selection part (where the user has chosen to use a textarea), as below:
if (trimmedResponse == 'manual') {
... (irrelevant code)
} else { //if paste is chosen
var createArray = function(howMany){
var pasteInput = document.createElement("TEXTAREA");
var makingArray = [];
document.body.appendChild(pasteInput);
pasteInput.rows = howMany;
let done = document.createElement("button");
done.innerHTML = 'Enter terms';
done.onclick = function(){
for (var j = 0; j < howMany; j++){
makingArray[j] = String((pasteInput.value).replace(/ /g,'').split('-')).split('\n');
}
pasteInput.style.display = 'none';
done.style.display = 'none';
}
document.body.appendChild(done);
return makingArray;
}
termArray = window.createArray(numOfTerms); //getting a variable holding the array from the prior function, to access later
}
The rest of the script.js file is made up of the regular subroutines - preload, setup, draw, and some initialisation and other small methods in the open scope before preload(), as below in a greatly reduced format:
let BG;
let translateEdit = document.createElement("button");
translateEdit.innerHTML = "Edit a translation";
translateEdit.style.position = 'absolute';
translateEdit.style.left = '50px';
translateEdit.style.top = '130px';
let list = "";
translateEdit.onclick = function () {
this.blur();
do {
replaceChoice = prompt("Which translation do you want to edit? (1-"+numOfTerms+") \n"+list+" \nOr enter any letter to leave this screen.");
} while (replaceChoice < 1 || replaceChoice > termArray.length)
termArray[replaceChoice-1][1] = prompt("What is the new translation for the term "+termArray[replaceChoice-1][0]+"?");
list = "";
for (let i = 0; i < numOfTerms ; i++){
list += ((i+1)+". ["+termArray[i][0] + "] - [" + termArray[i][1] + "]\n") //adds each term and translation in a user-friendly / clear display to the list variable for later display
}
alert("The term list currently looks as follows: \n"+list);
};
document.body.appendChild(translateEdit);
let temp1;
let temp2;
let temp3;
var performanceDisplay = "";
function preload() { //function loading image from file into variable
Helvetica = loadFont('Helvetica-Bold.ttf');
BG = loadImage('images/background.png');
}
function setup() { //function to create display/background using image file and dimensions and instantiate objects (character,terms,counters) as well as slider and icon to be displayed for it
alert("Below are the terms you have entered: \n" + list + "If any of the above are incorrect, use the edit buttons on the next screen to adjust terms or translations.");
speakericon = loadImage('images/speaker.png');
createCanvas(width, height);
... (further code in setup())
}
function draw() { //make background + objects visible on screen, allow them to act as they must, creating new terms when necessary, calling functions in class files such as player movement (calls all functions in classes throughout function) - all run every tick
image(BG, 0, 0, width, height); //set the display to the background image from BG variable in preload()
... (further code in draw())
}
In essence, I need to stop everything else from running until the button 'done' is clicked, and would appreciate any help with anything to achieve this.

Adding Next & Previous Buttons to modal with JavaScript

I have made a clean modal to use on a website to open images, everything works fine and is pretty nice.
Now I want to make a next image and previous image button for a better user experience.
I have a plan, so I find the index of the current image that is in the modal and I increment it by one on the next button, and decrement it by one on the previous button, HM ok seems easy enough. So how do I go about doing this?
this is my Modal code
window.onload = function() {
var imgArr = document.getElementsByClassName("myImg");
var modalWindow = document.getElementById("myModal");
var modalImg = document.getElementById("img01");
var caption = document.getElementById("caption");
var span = document.getElementById("close");
var modalBlock = document.getElementById("modalBlock");
for (i = 0; i < imgArr.length; i++) {
var picture = imgArr[i];
var list = Array.from(imgArr);
picture.onclick = function() {
openImg(this);
var index = list.indexOf(this);
console.log(index);
};
}
function openImg(pic) {
modalWindow.style.display = "block";
modalBlock.style.transform = "translateY(0%)";
modalImg.src = pic.src;
modalImg.alt = pic.alt;
caption.innerHTML = modalImg.alt;
imgIndex = picture[i];
bodyScrollLock.disableBodyScroll(myModal);
}
};
Now I have the open image that I've clicked on and its index, and I'm stuck on what to do next. I've found the w3 lightbox tutorial, but it's so different from my code I need to swap everything. Does anyone have an idea how I can do this with my own code?
A jsFiddle how it looks at the moment
https://jsfiddle.net/superVoja/eoyda1vh/15/
If you insist on building this from scratch then you will need to start thinking about what you should control with HTML and CSS and leave the rest to do with JavaScript.
I would use Modal window set with Html and hide it with CSS, then when image link and trigger fires I would bring modal to front. Using fadein fadeout, opacity and z-index to make sure that is on the front. Set background to black in order to get the Modal effect.
The faster way is to use library like Lightbox js
Then overwrite using CSS and maybe some js if need to in order to adjust to your liking.
Well, here is the answer I got myself if anyone reads this give yourself some time, you'll find the answer yourself!
I followed my code and did exactly the thing I was trying to do, I found the index of the image that is clicked, and then I just incremented it by one like this.
var next = this.document.getElementById("next");
var slideIndex = "";
for (i = 0; i < imgArr.length; i++) {
var picture = imgArr[i];
var list = Array.from(imgArr);
picture.onclick = function() {
var index = list.indexOf(this);
slideIndex = index;
openImg(imgArr[index]);
console.log(index);
};
}
next.addEventListener("click", function(event) {
openImg(imgArr[(slideIndex += 1)]);
});
It may not look pretty, but it's mine and I am proud of it!
And here is a link How it looks!

JavaScript: image slider changes only once upon clicking

I'm puzzled by the function of my JavaScript image slider since it changes the slide only once upon clicking next (I haven't worked on previous yet, but should be logical enough to re-adjust). The code is given by:
$(".room_mdts").click(function(event){
//get the target
var target = event.currentTarget;
var room = $(target).data("room");
currentIndex = parseInt($(target).attr('data-room'));
//First way, by reuse target (only inside this function)
$('#room_details_holder').show();
//The second, by using selectors
//remove all "selected" classes to all which have both "room" and "selected" classes
$('.room_exp.selected').removeClass("selected");
//add "selected" class to the current room (the selector can also be the target variable)
$('.room_exp[data-room='+room+']').addClass("selected");
});
var currentIndex = 0;
var adjIndex = currentIndex - 1,
items = $('.room_details .room_exp'),
itemAmt = items.length;
function cycleItems() {
var item = $('.room_details .room_exp').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
$('.room_next').click(function() {
adjIndex += 1;
if (adjIndex > itemAmt - 1) {
adjIndex = 0;
}
cycleItems(adjIndex);
cycleItems(currentIndex);
$('#room_name').text($('.room_exp:nth-child('+(adjIndex+2)+')').attr('title'));
});
$('.room_previous').click(function() {
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = itemAmt - 1;
}
cycleItems(currentIndex);
$('#room_name').text($('.room_exp:nth-child('+(currentIndex+1)+')').attr('title'));
});
$('#room_name').text($('[style*="inline-block"].room_exp').attr('title'));
});
The reason I had to introduce adjIndex is because without '-1' the slide changed by 2 on the first click, again, no idea why.
The Fiddle: https://jsfiddle.net/80em4drd/2/
Any ideas how to fix that it only changes once? (And also, the #room_name only shows after the click, does not show upon expanding).
Try this I rearranged your code a little bit:
made your currentIndex global and assigned with the adjIndex. If that's ok I will improve my answer:
If you click on the right arrow it goes to the end and comes back to the beginning.
url: https://jsfiddle.net/eugensunic/80em4drd/3
code:
function cycleItems() {
currentIndex=adjIndex;
var item = $('.room_details .room_exp').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
Okay, great thanks to eugen sunic for the little push that got me thinking!
I have finially cracked all of the pieces, although, I might have some extra unecessary bits of code, duplicates etc, but the functionallity is just perfect!
What I have edited:
I moved one of the closing brackets for the cycleFunction () closing bracket to the end of .click functions, that is to make the variable global (at least for those 3 functions)
I changed the title writing function from: $('#room_name').text($('[style*="inline-block"].room_exp').attr('title'));
to:$('#room_name').text($('.room_exp:nth-child('+(adjIndex+2)+')').attr('title'));
Added a few changes regarding .addClass/.removeClass to the $('.room_details_close').click(function(){.
Now, openning any of the thumbnails shows the title immediately (the right title), clicking '<<' or '>>' changes the slide to next and previous, respectively, while the title changes accordingly. Closing the expanded menu and clicking on a different thumbnail results in re-writing the currentIndex (hence, adjIndex too), so the function starts again with no problem.
Please feel free to use!
The new fiddle is: Fiddle

Animating dynamically created divs with javascript

I am trying to animate a dynamically created div with javascript, the id for the div is assigned when it is created, everything works fine until I attempt to animate one of the divs, I am trying this :
function start() // Called from a button click
{
var moveDiv= document.getElementById('Id0'); // Id0 is the Id of the div to move
animate(moveDiv); // Recursive animate
}
function animate(inDiv)
{
inDiv.style.left = parseInt(inDiv.style.left)+1+'px';
setTimeout(animate,20); // Recursive call
}
I know this is supposed to move the div infinitely to the left. However nothing happens at all and I cannot figure out why, I don't think its the fact that I dynamically create the divs as I have checked all the Id's and they all exist so I don't think its because it can't find Id0, but just incase here is a snippet of my div creation code :
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
var start = c.indexOf('"coursename":"') + 14;
var end = c.indexOf('","coursemark":"');
var CC = c.substring(start,end);
var start = c.indexOf('","coursemark":"') + 16;
var end = c.indexOf('%"')+1;
var CM = c.substring(start,end);
var idCount = i;
var div = document.createElement("div");
div.style.width = "180px";
div.style.height = "75px";
div.style.backgroundColor = "rgba(0,100,175,0.8)";
div.style.color = "white";
div.style.marginTop = "2%";
div.style.marginLeft = "50%";
div.id = "sortID"+idCount;
div.innerHTML = "Course Name : " + CC + " Course Mark : " + CM + " Id : " + div.id;
document.body.appendChild(div);
}
This code works fine however and creates the divs perfectly, I just can't get any div to move. Any help would be greatly appreciated.
Couple of problems...
function start() // Called from a button click
{
var moveDiv= document.getElementById('Id0'); // Id0 is the Id of the div to move
animate(moveDiv); // Recursive animate
}
There is no element with ID of Id0. All of your generated element IDs look like sortID...
And then...
function animate(inDiv)
{
inDiv.style.left = parseInt(inDiv.style.left)+1+'px';
setTimeout(animate,20); // Recursive call
}
inDiv.style.left has never been initiated
You're not passing inDiv through to your recursive animate call
So firstly check your element references. Then make sure you're setting the position of the div correctly, or handling scenarios where it isn't yet set. And finally make sure you pass inDiv through recursively.

Assigning dynamic <div> unique ID when they are created

This is related to dynamic div creation. I wanted to create an animation in which an object(bird) fly from ground to the sky (the background image-wrapper div). The bird is used as the child div of wrapper. Every time the button is clicked, I want to create new div tag with UNIQUE ID with bird as a background and use the code as below accordingly to show the animation. My code is not working and I cannot find my mistake being new to jquery and javascript.
Also, which one is better for efficiency? Creating unique ID for each tag or assigning them as an array value?
$(document).ready(function () {
bird_count = 0;
$("button").click(function () {
var bird = document.createElement('div');
bird.setAttribute('id', "bird" + bird_count);
wrapper.appendChild(bird);
num_var = 0;
while (num_var < 29) {
$("#bird").animate({
top: '-=5px',
right: '-=5px',
}, 50);
num_var = num_var + 1;
}
bird_count = bird_count + 1;
});
});
Let's assume your HTML is something like:
<button id='makeBird'>Make a new bird!</button>
<div id='wrapper'></div>
Which is reasonable for your JS code.
Let's see how we can write JS that avoids stuff like "#name"+number.
Ths following creates a single bird every time the button is clicked. It adds numbers to them.
var button = document.getElementById("makeBird"); // get the button and wrapper elements
var wrapper = document.getElementById("wrapper");
var counter = 0; //our counter
button.onclick = function () { // when you click on the button
var bird = document.createElement('div'); // make a new bird
var birdNumber = counter; // assign it a counter number
counter++; // and increase the counter
bird.className = "bird";
bird.onclick = function () { // when you click on it
alert("HI, I'm bird "+birdNumber); // it tells you which bird it is
}
$(bird).animate({ // when we create the bird, animate it
right: '-=400px',
}, 10000);
wrapper.appendChild(bird); // append our bird to the wrapper.
};
You can see a Working Demo Here
PS, if we place our JS code at the bottom of the <body> section of our code, we can avoid document.ready
Here is a jQuerified solution, in case you're into that.
Here is a jQuerified version wrapped in a loop that creates 29 birds on click
maybe this example can help:
$("button").click(function () {
var bird = document.createElement('div');
bird.className = 'bird'; // thanks #BenjaminGruenbaum
wrapper.appendChild(bird);
for(var num_var = 0; num_var < 29; num_var++) {
$(bird).animate({
top: '-=5px',
right: '-=5px',
}, 50);
}
});
you can use this
this is already present in jquery UI and generates OR removes id that are unique and generate on runtime by jquery UI
NOTE:- Jquery UI is a large library to solve this kind of problem.. so this answer is only applicable if you are already using jquery UI

Categories