Function not firing correctly on first click - javascript

I have a function that makes two buttons.
One button will auto scroll down and the other up.
It goes through an array and changes the button on every tap.
My problem is that I have to click the button twice to get it to work and then it does not get fired after that at all.
Is there a logic error in here I am not seeing?
What I want it the arrows to act like the twitter bootstrap image carousal. I want to click the arrows and have them take me to the next or previous section.
This is a screenshot of the the page and the arrows I am trying to change
IMG REMOVED
URL REMOVED
Sorry, I removed the img and url but with this site not being live yet, it shouldn't be viewed like that. I was in a pickle though.
I solved the problem. Read the comments if you have a similar one like this.
Thanks everyone!
$(function () {
var leftArrow = $('#left-arrow')
var rightArrow = $('#right-arrow')
rightArrow.bind("tap", rightTapHandler)
function rightTapHandler(event){
if (ai == 0) {
alert('0' + event)
ai = 1
controllerContainer.innerHTML = linkArrayForwards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayForwards[0] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else if (ai > 0) {
alert(ai)
ai++
controllerContainer.innerHTML = linkArrayForwards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayForwards[ai - 1] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else if (ai >= linkArrayBackswards.length) {
ai = linkArrayBackswards.length;
controllerContainer.innerHTML = linkArrayForwards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayForwards[ai - 1] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else {
alert('nothin')
return false
}
};
leftArrow.bind("tap", leftTapHandler)
function leftTapHandler(event) {
if (ai == 0) {
alert('0' + event)
ai = 1
controllerContainer.innerHTML = linkArrayBackswards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayBackswards[0] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else if (ai > 0) {
alert(ai)
ai--
controllerContainer.innerHTML = linkArrayBackswards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayBackswards[ai - 1] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else if (ai >= linkArrayBackswards.length) {
ai = linkArrayBackswards.length;
controllerContainer.innerHTML = linkArrayBackswards[ai] + '<div id="right-arrow" class="arrow"></div></a>' + linkArrayBackswards[ai - 1] + '<div id="left-arrow" class="arrow"></div></a>';
return
} else {
return false
}
};
})

From what i notised on your website, it alerts "0[option Option]" on the first click on any of the two arrows.
if (ai == 0) {
alert('0' + event)
ai = 1
"ai == 0" must be true.. It's the only alert with "0" in it and the only reason it would pop that alert, as far as i know & see.
Apart from that, once you have clicked OK on the alert, the arrows seem to work perfectly fine for me..
Edit
Are you sure you are declaring ai before the "if (ai == 0)" check?
If you aren't. remove the alert so the code looks like this (for both arrows):
if (ai == 0) {
ai = 1

Related

prev and next returning undefined instead page numbers in pagination

I am trying to create pagination with the below code and I am facing the problem to access page number ($clickedPageLink.dataset.page) when I click Prev and Next links. However, I am able to successfully get the page number when I click page number 1 to 5. Please find the plunker for reference Pagination. When click Prev and Next, console.log($clickedPageLink.dataset.page) is giving undefined. Can any one help to get the values for Prev and Next also as given in html?
let prevVal = 2;
let nextVal = 3;
let str = ['<nav class="pagination">'];
str.push('<ul class="pagination__pages">');
str.push('<li class="pagination__page pagination--previous">');
str.push('<a class="pagination__link" data-page="' + (prevVal - 1) + '" href="#">');
str.push('<span><i class="fas fa-angle-left"></i> Prev</span>');
str.push('</a></li>');
for (let plengthMn = 1; plengthMn <= 5; plengthMn++) {
str.push('<li class="pagination__page">');
str.push('<a class="pagination__link" data-page="' + plengthMn + '" href="#">' + plengthMn + '</a>');
str.push('</li>');
}
str.push('<li class="pagination__page pagination--next">');
str.push('<a class="pagination__link" data-page="' + (nextVal + 1) + '" href="#">');
str.push('<span>Next <i class="fas fa-angle-right"></i></span>');
str.push('</a></li>');
const $paginationList = document.getElementById('products-item_pagination');
$paginationList.innerHTML = str.join('');
const $paginationLinkMn = document.querySelectorAll('.pagination__link');
function attachEventToElementList(elmList, event, eventHandler) {
if(!elmList) {
return;
}
elmList.forEach(function(elm) {
elm.addEventListener(event, eventHandler);
});
}
attachEventToElementList($paginationLinkMn, 'click', goToPageMn);
function goToPageMn(event) {
const $clickedPageLink = event.target;
console.log($clickedPageLink.dataset.page)
}
And in my html, I have,
<div id="products-item_pagination" class="product-pagination"></div>
The problem with the above code is, the event is never firing up for anchor tag which is the parent of prev icon. Below css hack has solved the problem.
a > * {
pointer-events: none;
}

Add class to div in jQuery based on a date

I admit not being so great with JavaScript.
I've been tasked to build a utility that will run a check to see if a campaign date is going to expire in 2 weeks or less and add a class if it's going to.
The date is coming from a service and it's built (datatables map) as follows.
The data is coming back undefined but that's a different issue.
Any feedback would be greatly appreciated because I don't seem to be having any luck whatsoever.
Initially I had a date object in there but wasn't sure it was necessary.
/*HTML Rendered Out for that table cell (there are multiple but this is how it
comes out*/
<td class=" campaign_start_date small-screen small-screen-2-col">06/14/2017 -
<div class="campaign-end-date">06/29/2017</div></td>
JS
//Datatables Code & modified for our project
{title:ax.L(114), class:'campaign_start_date small-screen small-screen-2-col', data:function(row, type, val, meta) {
var campaignEndDate = ax.Utils.deNull(row.campaign_end_date, '');
campaignEndDate = ax.Utils.RFCFormat(campaignEndDate, { excludeTime: true });
var campaignStartDate = ax.Utils.deNull(row.campaign_start_date, '');
campaignStartDate = ax.Utils.RFCFormat(campaignStartDate, { excludeTime: true });
var campaignDateString;
if (campaignEndDate && campaignStartDate ) {
campaignDateString = campaignStartDate + ' - ' + '<div class="campaign-end-date">' + ax.Utils.campaignEndDateAlert(campaignEndDate) + '</div>';
} else {
if (!campaignEndDate && campaignStartDate) {
campaignDateString = campaignStartDate + ' - ? ';
}
else if (!campaignStartDate && campaignEndDate) {
campaignDateString = ' ? - ' + campaignEndDate;
}
else {
campaignDateString = ' ';
}
}
return campaignDateString
//My attempt at doing this from the Utility file - the code that i'm having no luck with.
publicMethods.campaignEndDateAlert = function (data) {
var campaignDateEnd = data.campaign_end_date;
var $orderTable = $('#order-table');
var $campaignDate = $orderTable.find('.campaign-end-date')
if (campaignDateEnd <= campaignDateEnd + 86400000) {
$campaignDate.addClass('green');
}
}

Leaving and re-entering a photo gallery doubles the amount of pictures you go through whenever you click the Previous/Next photo button. Any idea why?

I'm making a photo gallery application to better understand dynamic content.
Here is the URL so you can get a better understanding:
http://claytonkinder.github.io/Day9-Project/
Here is a Codepen of it to get a better look at the code.
The next/previous arrows aren't showing due to some funky styling issues on the photo page but you can still interact with them. They're located 64px away from roughly the middle of each photo and the cursor will turn into a pointer while over them.
http://codepen.io/anon/pen/WvjoLP
My issue:
Whenever you click on a single photo to view it, click on the "Go back to [Album]" button, and then click on a new photo, the Previous/Next arrows will double the amount of photos they go through. So the very first time you view a photo and go to either the next or previous photo it will go Photo 1, Photo 2, Photo 3. If you go back to view the album, click on another photo to view it, and then click on either the next or previous arrow, it will go Photo 1, Photo 3, Photo 5. After a few times of doing this, clicking the next or previous arrow will effectively do nothing and you will get stuck on the same photo.
What I Know:
After slapping a bunch of console.logs everywhere, I found out what seems to be going wrong, I just don't know why or how to fix it. After leaving and re-entering an album, clicking on the Next/Previous button seems to execute everything within that click event double what it did last time. I am not sure why this happens.
Here is the code that involves clicking on the Next/Previous arrows.
$('body').on('click', '.albumPageGalleryBlock', function(e){
e.preventDefault();
activePhoto = $(this).attr('rel');
photoPageConstructor();
$allPages.removeClass('active');
$photoPage.addClass('active');
$('body').on('click', '#photoPagePhotoBlock > div', function(e){
e.preventDefault();
if ($(this).hasClass('prevPhoto')) {
// Breaks name of activePhoto into array
if (typeof activePhoto === 'string') {
var activePhotoArray = activePhoto.split("");
} else if (typeof activePhoto === 'object') {
var activePhotoArray = activePhoto.title.split("");
}
// console.log('Prev ActivePhotoArray: ', activePhotoArray);
// Removes last character from activePhotoArray
var popped = activePhotoArray.pop();
// console.log('Prev Popped: ', popped);
// Subtracts 1 from the number removed in the last step
var poppedMinus = (Number(popped) - 1);
// console.log('Prev PoppedMinus: ', poppedMinus);
// If activePhoto is less than 1, it loops around to the end of the array, in this case it's 6.
if (poppedMinus < 1) {
for (var i=0; i<albums.length; i++) {
if (activeAlbum === albums[i].title) {
poppedMinus = albums[i].photos.length;
// console.log('Prev PoppedMinus ChangeTo6: ', poppedMinus);
}
}
}
// Pushes the newly subtracted number onto the end of the array
var newActivePhoto = activePhotoArray.push(poppedMinus);
// console.log('Prev newActivePhoto: ', newActivePhoto);
// Joins the array back into a string
newActivePhoto = activePhotoArray.join("");
//console.log('Prev newActivePhoto Joined: ', newActivePhoto);
console.log('Currently Displaying Photo Title: ', newActivePhoto);
activePhoto = newActivePhoto;
photoPageConstructor(newActivePhoto);
} else if ($(this).hasClass('nextPhoto')) {
// Breaks name of activePhoto into array
if (typeof activePhoto === 'string') {
var activePhotoArray = activePhoto.split("");
} else if (typeof activePhoto === 'object') {
var activePhotoArray = activePhoto.title.split("");
}
// Removes last character from activePhotoArray
var popped = activePhotoArray.pop();
// Adds 1 from the number removed in the last step
var poppedPlus = (Number(popped) + 1);
// console.log('Next PoppedPlus: ', poppedPlus);
// If activePhoto is greater than the length of the currentAlbum, it loops around to the beginning of the array.
if (poppedPlus > albums.length) {
for (var i=0; i<albums.length; i++) {
if (activeAlbum === albums[i].title) {
poppedPlus = 1;
}
}
}
// Pushes the newly subtracted number onto the end of the array
var newActivePhoto = activePhotoArray.push(poppedPlus);
// Joins the array back into a string
newActivePhoto = activePhotoArray.join("");
// console.log('Currently Displaying Photo Title: ', newActivePhoto);
activePhoto = newActivePhoto;
photoPageConstructor(newActivePhoto);
// photoPagePhotoBlockConstructor(newActivePhoto);
}
});
});
Here is the code that builds the individual photo page:
function photoPageConstructor(actPho) {
$('#photoPage').html("");
var constructStr = "";
var fetchedActiveAlbum = fetchActiveAlbum();
if (actPho !== undefined) {
var fetchedActivePhoto = actPho;
} else {
var fetchedActivePhoto = fetchActivePhoto();
}
constructStr += '<div id="photoPageNavWrapper">';
constructStr += '<a id="photoPageBackBlock" href="#">';
constructStr += '<div id="photoPageBackIcon"><i class="fa fa-chevron-left"></i></div>';
constructStr += '<div id="photoPageBackText">';
constructStr += 'Back to ' + fetchedActiveAlbum.title;
constructStr += '</div></a>';
constructStr += '<div id="photoPageTitleBlock"><h1>';
constructStr += photoPageTitleConstructor(fetchedActivePhoto);
constructStr += '</h1></div></div>';
constructStr += '<div id="photoPagePhotoWrapper">';
constructStr += photoPagePhotoBlockConstructor();
constructStr += '</div>';
$('#photoPage').append(constructStr);
$('#photoPageBackBlock').on('click', function(e){
e.preventDefault();
albumPageMainConstructor();
$allPages.removeClass('active');
$albumPage.addClass('active');
});
}
function photoPageTitleConstructor(actTitle) {
var constructStr = "";
var fetchedActivePhoto = fetchActivePhoto();
if (actTitle !== undefined) {
if (typeof actTitle === 'object') {
constructStr += actTitle.title;
} else {
constructStr += actTitle;
}
} else {
constructStr += fetchedActivePhoto.title;
}
return constructStr;
}
function photoPagePhotoBlockConstructor(actPho) {
$('#photoPagePhotoWrapper').html("");
var constructStr = "";
var fetchedActiveAlbum = fetchActiveAlbum();
if (actPho !== undefined) {
var fetchedActivePhoto = actPho;
if (typeof actPho === 'string') {
activePhoto = actPho;
} else {
activePhoto = actPho.title;
}
constructStr += '<div id="photoPagePhotoBlock" rel="';
constructStr += activePhoto;
constructStr += '">';
constructStr += '<div id="prevPhoto" class="prevPhoto"><i class="fa fa-chevron-left"></i></div>';
for (var i=0; i<fetchedActiveAlbum.photos.length; i++) {
if (fetchedActiveAlbum.photos[i].title === activePhoto) {
constructStr += fetchedActiveAlbum.photos[i].imageTag;
}
}
constructStr += '<div id="nextPhoto" class="nextPhoto"><i class="fa fa-chevron-right"></i></div>';
constructStr += '</div>';
$('#photoPagePhotoWrapper').append(constructStr);
} else {
fetchedActivePhoto = fetchActivePhoto();
constructStr += '<div id="photoPagePhotoBlock" rel="';
constructStr += fetchedActivePhoto.title;
constructStr += '">';
constructStr += '<div id="prevPhoto" class="prevPhoto"><i class="fa fa-chevron-left"></i></div>';
constructStr += fetchedActivePhoto.imageTag;
constructStr += '<div id="nextPhoto" class="nextPhoto"><i class="fa fa-chevron-right"></i></div>';
constructStr += '</div>';
return constructStr;
}
}
This code is pretty convoluted at points, as I'm mainly focusing on just getting it to work before I go back and trim it down.
Thank you for any and all help.
Fixed it like 5 minutes after taking 20 minutes to get this post together. :/
Turns out all I needed to do was move that function that's called whenever I click on the Next/Prev button outside of the one that it's currently nested in.

How to show two div when user scroll down using jquery?

Can anyone please tell me how to show two divs when the user scroll down using jquery.I want to push values on the array .Is it possible to add a div on the bottom.As we add when user scroll to top ?
http://jsfiddle.net/Gbd3z/2/
$("#fullContainer").scroll(function () {
// top
if ($(this).scrollTop() === 0 && pages.length) {
console.log("up"+pages);
var stringLoad = "page_" + pages.length;
$("<div id='" + stringLoad + "'>" + pages.pop() + "</div>").prependTo($("#fullContainer"));
$('#fullContainer').children().slice(3).remove()
}
if ($(this).scrollTop() >= $(this)[0].scrollHeight - document.body.offsetHeight) {
console.log("down");
}
});
I'm not entirely sure what you're asking for, but does this do it?
http://jsfiddle.net/luken/R24TH/
var pages = [page_1, page_2, page_3, page_4,page_5];
var lastLoadedPageIndex = -1;
var $container = $('#fullContainer');
addNextPageToContainer();
function addNextPageToContainer () {
lastLoadedPageIndex++;
if (lastLoadedPageIndex < pages.length) {
$( '<div id="page_'
+ lastLoadedPageIndex
+ '" class="page">'
+ pages[lastLoadedPageIndex]
+ '</div>'
).slideDown().appendTo( $container );
}
}
$container.scroll(function(){
if ($container.scrollTop() === 0 && pages.length) {
console.log("up");
} else if ($container.scrollTop() >= $container[0].scrollHeight - document.body.offsetHeight) {
console.log("down");
addNextPageToContainer();
}
});

Can't find the issue: javascript/jQuery

I have the following function that gets called on the KeyDown event of a link.
Basically I'm trying to move down the table (the application calls it a ListBox). In the first loop what I'm trying to do is see if they use the mouse to click inside the table first and my hope was to find the row value and then manipulate the class (highlight) from there.
Unfortunately right now I'm not even getting that far. When the screen loads and I press the down button, the current row (0) has it's class changed as well as row (1). But on the next down button press the tr_lst says it is undefined. Which then throws the loop off and then I get all sorts of errors.
I tried to implement a jsfiddle, however, I couldn't get it working. But you can see some of the code I'm trying to implement.
function xKeyDown(event,ListBoxVal){
var tr_lst = $('#' + ListBoxVal).find('tr[class="LUGridRowHighlight"]');
var iCount = 0;
for (iCount = 0; iCount <= $('#' + ListBoxVal + ' tr').length; iCount++){
if($('#' + ListBoxVal + ' tr:eq('+iCount+')').attr('id') == tr_lst.attr('id')){
lstRow = iCount;
break;
}
}
if (event.keyCode == 40){
//arrow down
if(parseInt(lstRow) < $('#' + ListBoxVal + ' tr').length)
{
if(parseInt(lstRow) == 0){
document.getElementById(ListBoxVal).focus();
lstRow +=1;
document.getElementById($('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight') .addClass('LUGridRow');
}else{
document.getElementById($('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$('#' + ListBoxVal + ' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight') .addClass('LUGridRow');
lstRow +=1;
}
}
...
Update:
After looking into this further... It appears that when I click the down arrow more than once the following code is causing an error:
var tr_lst = $('#' + ListBoxVal).find('tr[class="LUGridRowHighlight"]');
When I try to print this out it is 'undefined'
I'm wondering since I am manipulating the class via jQuery do I need to add a .live somewhere to the find? As I believe when elements are manipulated dynamically the .live comes into play. Any suggestions?
Try this
function xKeyDown(event,ListBoxVal){
var $listBoxVal = $('#' + ListBoxVal);
var trs = $listBoxVal.find('tr');
var tr_lst = $listBoxVal.find('tr.LUGridRowHighlight');
var tr_lst_id = tr_lst.attr('id');
var iCount = 0;
for (iCount = 0; iCount <= trs.length; iCount++){
if($listBoxVal.find('tr:eq('+iCount+')').attr('id') == tr_lst_id){
lstRow = iCount;
break;
}
}
if (event.keyCode == 40){
//arrow down
if(parseInt(lstRow) < $listBoxVal.find('tr').length)
{
if(parseInt(lstRow) == 0){
$listBoxVal.focus();
lstRow +=1;
$("#"+$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$listBoxVal.find(' tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight').addClass('LUGridRow');
}else{
$("#"+$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').attr('id')).focus();
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').addClass('LUGridRowHighlight');
$listBoxVal.find('tr:eq('+parseInt(lstRow)+')').prev().removeClass('LUGridRowHighlight').addClass('LUGridRow');
lstRow +=1;
}
}
...

Categories