Trigger event not working or suspected passing on index - javascript

.full-arrow is an arrow that selects the next page. .full-navigation is a navigation bar, quite simply boxes in a line that change colour when you select them. The rest of the function isn't on here but you get the general idea.
When I create a trigger event to the function below the first one, it goes through okay but I'm unsure whether it's not picking up the index() or whether it's just not working at all. Weirdly, it works the first time but I think that's because the same_page variable is declared as 0 in the beginning.
The reason I'm also doubting whether it's the index() not being passed on is because the alert("foo"); isn't coming up.
$(".full-arrow").click(function() {
$(".full-navigation li:eq(" + same_page+1 + ")").trigger("click");
});
$(".full-navigation li").click(function(event) {
//alert("foo");
//alert(same_page);
same_page = $(this).index();
if(same_page == $(this).index()) { return false; }
});

Where are you getting the same_page variable from? Try using parseInt( same_page, 10 )--I have a hunch it's actually a string.

Related

Asking if variable is equal to an integer inside jquery click not working

The title really explains most of it, but basically, this should alert when I get the click the element, but it doesn't. It also does work when I put the alert() outside of the if, and in the beginning of the jquery on click. Here's my code:
var hasClickedWelcome = 0;
//Onclick event
$(".menu-welcome" ).click(function() {
var welcomeButton = document.getElementByClassName("menu-welcome");
if(hasClickedWelcome == 0) {
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
} else {
welcomeButton.classList.remove("menu-welcome-clicked");
hasClickedWelcome = 0;
}
});
Your if statement has no meaning
if(hasClickedWelcome == hasClickedWelcome)
This will always return true, you'll always hit this code no matter what:
alert("hello");
$(".menu-welcome").addClass("menu-welcome-clicked");
hasClickedWelcome = 1;
Therefore, you have a clear logic problem.
Edit: See Daniel Beck suggestion on comments section
Initially, you have syntactic error, there is no inbuild function like document.getElementByClassName() (unless its your custom function), so clearly even if you put your alert in beginning of click it won't work.
Also, you are checking if(hasClickedWelcome == hasClickedWelcome) which does not make sense.
Use: document.getElementsByClassName("menu-welcome"); to get array of nodes having the class. Then, rest of your logic accordingly.
//Onclick event
$(".menu-welcome" ).click(function() {
// in jQuery "this" refers to the element that was selected in a callback
// it looks like toggleClass is really what you're looking for
$(this).toggleClass("menu-welcome-clicked");
});

Changing Array causing glitches with splice

I have a form event which takes entered values and constructs an array out of them using the following:
keywordArray = []
var getVal = $('#search').val();
if(getVal.length > 1){
keywordArray.push(getVal);
$('.test').on('click', function(){
removeTag(this, getVal);
});
$('#search').val("");
}
My remove function then looks as follows:
function removeTag(el, getVal){
var index = keywordArray.indexOf(getVal);
keywordArray.splice(index, 1);
}
There is no problem when removing a value for the first time as the index is in sync, but once a value is removed the index changes and it seems that JS isn't staying in sync with the updated index, so when I remove another value it glitches with a -1 on splice and will remove all values.
I see two problems: Your removeTag function and the way it is called.
First of all, removeTag() does not need the element, so remove the el parameter if it is really not needed. Second, it should do nothing when the given string does not occur in the array:
function removeTag(val){
var index = keywordArray.indexOf(val);
if (index >= 0) keywordArray.splice(index, 1);
}
The second problem might be related to this part of your code:
$('.test').on('click', function(){
removeTag(this, getVal);
});
I suspect that you don't want to register a click handler for all '.test' elements because you refer to this in the next line but this is not used in the removeTag function (see above). In case there are several '.test' elements, you should make sure that removeTag() is only called with the value that corresponds to the clicked '.test' element. Currently you call removeTag() several times for each click -- once for each '.test' element.
The main problem is pointed out by #vijayP in the comments. Here is a first possible solution.
When adding a tag, use the data attribute to associate the tag with the remove button (el):
function addTag(el, value) {
$(el).data('value', value).on('click', removeTag);
}
I assume you have a separate remove button for each tag. Then, the click handler function can look like this (with the check for a correct index):
function removeTag(){
var index = keywordArray.indexOf($(this).data('value'));
if (index > -1) keywordArray.splice(index, 1);
}

For loop index undefined in IE9 for initial pass

On this page: http://koncordia.marketingassociates.com/19892arc/
I have a slideshow that I created custom prev/next links for. Each selection you make on the page advances it one slide forward. The progress bar at the top allows you to click a previous slide, and jump more than one back if you want (you can go from step 4 or step 1 for example).
This multi-step jump works fine in all the current major browsers, but the client uses IE9, and this is where I do not understand the source of the issue.
The following are the relevant methods in this issue. To mimic a user jumping back one or more slides I have a for loop iterate over simulatePrevClick() as many times as necessary; it's not sexy but it works.
The issue arises on the initial pass in IE9. The console spits out "undefined" for the first pass, but it says 0 for all other browsers (including IE 10 and 11) which is correct. If I remove the method call within the loop the iteration works perfectly, so it has something to do with the .click() event or way the method is called, but I don't know what.
No matter what, IE9 will show the immediate previous slide no matter how many they click back; the progress bar be out of sync if they click back more than one in this instance. The undefined result is not showing as an error, either.
//Highlight the right number of progress buttons
highlightProgressBar: function( slideNumber ) {
$(".btn-progress").attr('disabled', 'disabled').removeClass('active'); //Disabled all
$("#progress-wrapper a:lt(" + slideNumber + ")").removeAttr('disabled'); //Disable select number
$("#progress-wrapper a:eq(" + (slideNumber - 1) + ")").addClass('active'); //Add active to the specified button clicked
},
simulateNextClick: function () {
//The value of this must match what the responsiveslides function creates for the prev/next buttons (seen when you inspect element)
$(".transparent-btns_nav.transparent-btns1_nav.next").click();
},
simulatePrevClick: function () {
//The value of this must match what the responsiveslides function creates for the prev/next buttons (seen when you inspect element)
$(".transparent-btns_nav.transparent-btns1_nav.prev").click();
},
toggleProgressBar: function( clickedSlideNumber, activeSlideNumber ) {
var numSlides = activeSlideNumber - clickedSlideNumber;
for (var i=0; i < numSlides; i++) { //Anticipate user may click more than one step back
this.simulatePrevClick();
console.log(i); // **shows "undefined" on first pass in IE9 only**
}
this.highlightProgressBar(clickedSlideNumber);
}
Try to move the var i = 0 declaration out of the loop.
var i = 0;
for (; i < numSlides; i++) {}
It's really strange that that should happen.
This is just a guess, but I looked through the rest of your source code, and its possible that the root of your problem could be due to whenever you actually implement your toggleProgressBar function, in this area:
$(".btn-progress").click(function() {
var currentSlideID = $("#progress-wrapper").find('a.active').attr('id').split("-");
var clickedSlideID = $(this).attr('id').split("-");
slideFn.toggleProgressBar( clickedSlideID[1], currentSlideID[1] );
});
If I see right, your toggleProgressBar wants to accepts two numbers. However, what you're passing in are string literals:
slideFn.toggleProgressBar( "2", "1" );
ID attributes are output as strings, not numbers. I just tested the following in Chrome, and it worked:
"2" - "1" === 1 //true
This is because I guess V8 (Chrome's JS engine) coerces the two string literals into numbers. However, (while I have not tested it), this tells me that it's possible that IE might not be coercing the two strings into numbers (like I said, I don't know this for a fact, but this is something you might try debugging). Try this and see if it has any effect:
//first option
slideFn.toggleProgressBar( +clickedSlideID[1], +currentSlideID[1] );
//the + sign will typecast your strings into numbers
//second option
slideFn.toggleProgressBar( parseInt(clickedSlideID[1]), parseInt(currentSlideID[1]) );
However, in my experience, parseInt runs a little bit slower than using + to typecast the strings into numbers.
IE uses the Chakra JS engine, which I believe follows the standards of ECMAScript 3, which is from 1999. I haven't read through the standard, but it's worth considering the possibility that it has something to do with the issue.
Edit
Here's your problem:
$("#progress-wrapper").find('a.active') ==> []
The first time, there are no a.active elements. Thus, whenever you try to call split on an empty array, it throws a TypeError.
You need to give your first .btn-progress the class active, because the first time around, your first .btn-progress looks like this:
1
There's no active class. Only subsequent .btn-progress elements receive the class active whenever you click the .btn-continue. Your first one never does. Therefore, clickedSlideID[1] and currentSlideID[1] are undefined the first go around. It probably breaks in IE9 because IE9 doesn't understand i < undefined, but it's possible that other more modern browsers go ahead and execute anyway.
Somewhere in the beginning of your code, then, you need to do something like this:
$('.btn-progress').eq(0).addClass('active');
I just tried this in the console on your page, and it worked just fine. After I added the class active to the fist .btn-progress, currentSlideID[1] was now 1, and not undefined.

Preventing "too much recursion" error in jQuery

EDIT**
I have this click event
$('.next-question').click(function () {
$('td').removeClass('highlight-problem');
var r = rndWord;
while (r == rndWord) {
rndWord = Math.floor(Math.random() * (listOfWords.length));
}
$('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('highlight-problem');
$('td[data-word=' + word + ']').removeClass('wrong-letter').removeClass('wrong-word').removeClass('right-letter');
var spellSpace = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('right-word');
if (spellSpace) {
$('.next-question').trigger('click');
} else {
$("#hintSound").attr('src', listOfWords[rndWord].audio);
hintSound.play();
$("#hintPic").attr('src', listOfWords[rndWord].pic);
$('#hintPic').show();
$('#hintPicTitle').attr('title', listOfWords[rndWord].hint);
$('#hintPicTitle').show();
}
});
When debug in the console it says too much recursion meaning it is in some sort of endless loop at this point. I think it is because of the trigger("click") event in the if statement, because I seen something similar online.
Basically, I want to say, if given word has the class right-word then move on (hence the trigger), else ...
Is there another way to write it that will not crash?
Here is a fiddle: http://jsfiddle.net/Dxxmh/112/
INSTRUCTION: Click the letters on the right to spell the highlighted area in the grid (The images to help you spell the words are not available in a fiddle so you have to spell them using the console, by looking up the td's)
I would do something like this:
if (spellSpace) {
if(score.right != 4)
$('.next-question').trigger('click');
I see like if(score.right == 4) means the end of game. After it is ended - you have no words (or just have no "right" words, not sure) at all and that is why it never stops. It just triggers click forever instead of stop doing anything and wait for user to click Restart button.
I guess that condition is not enough. Not sure how number of wrong words is counted and handled. But it should be enough to move forward and build correct condition based on your programm logic. Any recursion you start (and you start it with trigger("click")) must have a stop condition.
.trigger('click') will just invoke the listener once more. Did you intend to follow the link only in that circumstance? In that case you could return false in your else scenario.
This isn't a jQuery issue: you're manually triggering the same event from within the handler:
$('.next-question').trigger('click');
Now, this will cause an infinite loop if you're not careful. Best way to fix this is not to invoke the handler by triggering the event a second time, but by calling it using a function name:
$('.next-question').click(function callMe(event)
{
//replace: $('.next-question').trigger('click');
//with this:
if (spellSpace && event)
{//also check if the event has been passed
callMe.apply(this,[]);//don't pass event for recursive call
}
});
Try to use this:
$('.next-question').click(function (event) {
event.preventDefault();
});

Javascript if statement not working as intended

If you look here and try to click on the voting arrows, you'll see my problem. Now compare that to the homepage (click logo). Try voting there. The arrows change image based on vote. I also use a in_array() function to determine what the user has voted on and it produces the correct voting icon. This all works fine on the submission page I linked to. However, again, if you try clicking on the links, it always defaults to the else statement in this Javascript function:
I'll only show the function for liking, as I'm having the identical problem for the dislike.
function getVote(filename, num, idnum, user)
{
var like = document.getElementById('like_arrow' + num);
var dislike = document.getElementById('dislike_arrow' + num);
if (like.src.indexOf('../vote_triangle.png')!=-1 && dislike.src.indexOf('../vote_triangle_flip.png')!=-1) {
like.src = '../vote_triangle_like.png';
(AJAX to alter rating here)
} else if (like.src.indexOf('../vote_triangle.png') != -1) {
like.src = '../vote_triangle_like.png';
dislike.src = '../vote_triangle_flip.png';
(AJAX to alter rating here)
} else {
like.src = '../vote_triangle.png'; // Always defaults to this
(AJAX to alter rating here)
}
}
In case you're wondering, the num variable is what I use on the front page to differentiate between the submissions, they increment by one for each one. In this though, I just made that value blank in the function so it shouldn't affect anything. Might be my problem though, but I can't see how.
Thanks!
like.src isn't going to contain ..\. It may be as simple as removing that part.

Categories

Resources