javascript if condition not working? - javascript

I am sitting like hours in front of the following code snippet and can not get it running like I want.
Basically this code creates a navigation menu on right click, but a click on the switcher should turn off this function and on the next click it gets turned on again.
Everything works fine (like expected), just the little if statement on line 12 ( if ( switcher % 2 == 0 ) ) does not work like expected, meaning the code within it always gets executed whether var switcher is even or not even. I also tried other conditions like "> 0" and so on but the code within it always gets executed.
$(document).ready(function () {
/* Set switcher to zero */
switcher = 0;
/* If switch gets clicked increment var switcher*/
$('#guidenavschalter').click(function () {
switcher++;
return false;
});
/* If var switcher is even execute following code, if not do nothing of this*/
if (switcher % 2 == 0) {
/* do not display right click browser menu */
document.oncontextmenu = function () {
return false;
};
/* if click within #page excluding area of #newid */
$('#page:not(#newid)').mousedown(function (e) {
/* if right click */
if (e.button == 2) {
/* if #newid already exist display it again */
if ($('#newid').length) {
$('#newid').css({
"display": 'block'
});
$('#newid').css({
"top": e.pageY + 'px'
});
$('#newid').css({
"left": e.pageX + 'px'
});
/* if it does not exist create and display #newid */
} else {
var $div = $('#block-bookoblock-book-outline').clone().attr('id', 'newid');
$('body').append($div);
$('#newid').css({
"top": e.pageY + 'px'
});
$('#newid').css({
"left": e.pageX + 'px'
});
$('#newid').css({
"position": 'absolute'
});
return false;
}
}
/* if left click hide #newid */
if (e.button == 0) {
$('#newid').css({
"display": 'none'
});
}
return true;
});
}
});

Your code basically is
switcher = 0;
... some irrelevant code here (the callback is not executed right now)
if ( switcher % 2 == 0 ) {
So no wonder the test always pass.
What you probably want is to put the if inside the callback, so that it's tested each time you click :
var switcher = 0;
$('#guidenavschalter').click(function(){
switcher++;
if ( switcher % 2 == 0 ) {
...
}
return false;
});

switcher = 0; // created outside the click event handler
and you're increment the value inside click event handler. Therefore it is always zero.
You should go through Scoping in JavaScript
From comment, you're interested to know more about variable scope in Javascript then
check out this SO answer

I don't think it is the condition switcher % 2 == 0 that is problematic here.
You have hooked events in case of true but is there an Else statement that unhooks those events so that the original functionality is resumed? i.e. Right click create default context menu.
Update:
In order to resume original functionality, call
document.oncontextmenu = null;
in else part.
Also, you need to define $('#page:not(#newid)').mousedown(function (e) { only once (outside of if/else ) and then use the switcher variable to determine whether to call the functionality or not.
In short, you need the following
$(document).ready(function () {
/* Set switcher to zero */
switcher = 0;
/* If switch gets clicked increment var switcher*/
$('#guidenavschalter').click(function () {
switcher++;
return false;
});
document.oncontextmenu = function() {
if ( switcher % 2 == 0 ) {
return false;
} else {
return true;
}
};
/* if click within #page excluding area of #newid */
$('#page:not(#newid)').mousedown(function (e) {
if (switcher % 2 == 0) {
// do stuff
} else {
// do nothing
}
});
});

Related

1 line of code (console.log), two emplacement in the code = two results differents

The problem I encountered is with the jQuery Selector that returns me two different answers for the same line of code :
console.log($('.page_container')[3]);
In my navigation fonction using arrows of the keybord, this line would return me the content of this div including the parent '.page_container'.
This is exactly what I don't want since I need it as an object.
function checkKey(e) {
var actualScroll = $('.main').scrollTop();
var scrollTo = $('.page_container').height();
console.log($('.page_container')[3]);
if (e.keyCode == '38' && working == false) {
working = true;
// up arrow
$(".main").animate({
scrollTop: actualScroll - scrollTo,
}, 1000, 'easeInOutExpo', function () {
working = false;
});
} else if (e.keyCode == '40' && working == false) {
working = true;
// down arrow
$(".main").animate({
scrollTop: actualScroll + scrollTo,
}, 1000, 'easeInOutExpo', function () {
working = false;
});
}
}
$(document).ready(function () {
//ArrowsNavigations
document.onkeydown = testArrows;
});
But anywhere else in the code, it would return me the normal thing, the object version with all its original properties.
Edit :
Here is the fiddle but I don't get why I don't have the same results, anyways on this fiddle whenever I select my entire array of '.page_container' I get the object sample but if I select a particular index of this array I'll get the html of this occurence.
On my local version, the selector returns me the html content only when it's called in the checkKey function.
I think you do get an object. It's just the browser's way of displaying things.
Try this:
console.log($('.page_container')[3].id);

Using shift key and click to go to the next slide

Hei guys, i added these lines of code as javascript on succes of a click box in captivate :
document.onkeydown = function (e) {
if (e.keyCode == 16) {
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', 5);
}
};
It does good what it does but after first atempt even if im on another slide and i press shift key it goes to slide 5 :( Another question is, how to set an mousedown and onkeyup event on same button. What i try to achieve is to jump to next slide if i press shift key and i click on a click box.
EDIT: new code:
document.onmousedown = function (e) {
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5 && e.keyCode == 16){
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide' , 5);
}
};
As i think it, should fire the function when i click on it, BUUUT , unfortunately it doesnt work... seems like Captivate doesnt recognize onmousedown event :|
RE-EDIT : i figurate out how to make it work. Here's the code :
document.onkeydown = function(e) {
var currentFrame = document.Captivate.cpEIGetValue('m_VarHandle.rdinfoCurrentFrame');
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5 && e.keyCode == 16){
document.Captivate.cpEISetValue('m_VarHandle.rdcmndGotoFrameAndResume' , 491);
}
};
document.onkeyup = function(e) {
var currentSlide = document.Captivate.cpEIGetValue('m_VarHandle.cpInfoCurrentSlide');
if(currentSlide == 5){
document.Captivate.cpEISetValue('m_VarHandle.rdcmndGotoFrameAndResume' , 485);
}
};
Now everything's just PERFECT! its exactly what i wanted to do... but it works only on localhost... only when i press F12 in Captivate :( if i try to run exported swf or html from captivate it crush :((( Any ideea ?
var slide = 4;
document.onkeydown = function (e) {
if (e.keyCode == 16) {
slide++;
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', slide);
}
};
Bassically you want to increment the position (second argument of cpEISetValue), in your code, you always set it to 5. Also make sure to reset it when it reaches the max slider position.
You can check the SHIFT key inside the click:
var slide = 4;
$('body').click( function (e) {
if (e.shiftKey) {
slide++;
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', slide);
}
});
check here
If you want to set a click with a shift key you can use this:
$(document).click(
function(e){
if(e.shiftKey){
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', 5);
}
}
);
the same works with ctrlKey, and altKey
And to change the page fine you need a control variable like this:
var current_page = 1;
$(document).click(
function(e){
if(e.shiftKey){
current_page++
document.Captivate.cpEISetValue('m_VarHandle.cpCmndGotoSlide', current_page);
}
}
);
I think this is the final code that you need (you maybe need to change document to an id or class that you are using like "#element_id" or ".element_class")

Jquery trigger on keypress

I am Using wordpress as cms
I have made a code which Runs a like() function when i press the left key
i try to trigger .love in like() Function
but it doesnt works
Here is my Code
var h2top = 0;
function like(){
scrollTop = jQuery(window).scrollTop();
jQuery('.container .post').each(function(i, h2){ /* loop through article headings */
h2top = jQuery(h2).offset().top ; /* get article heading top */
if (scrollTop<h2top-19) { /* compare if document is below heading */
alert("Ram");
jQuery(this).find('.love').trigger( "click" );
return false; /* exit function */
}
});
}
Here is the jquery code for Keypress events
jQuery(document).ready(function ($) {
$(document.documentElement).keyup(function (event) {
var direction = null;
// handle cursor keys
if (event.keyCode == 37) {
// go left
like();
$("#sad").closest('div').addClass('left');
alert("left");
} else if (event.keyCode == 39) {
// go right
alert("right");
}
});
});
Just using alert() to check whether the code is running or not
Just
$(document).keyup(function(e) {
alert (1);
// use event.which instead of keyCode
});
Instead of
$(document.documentElement).keyup(function (event) {
Other error, in your like function at the line jQuery(this).find('.love').trigger( "click" );
this is not the jQuery context, you must use $(this) like
jQuery($(this)).find('.love').trigger( "click" );
Example (updated)
http://jsbin.com/azUnUlO/1/

if statement and popup case

I have a textbox. its name is PhoneNumber. I want to do a popup if len(input value)=0.
When I do a tag it doesn't work. (I looked in debug mode)
When I do it in an another Jq script which is already works. it works but popup window stay screen only a few mil seconds so I can not do anything.
I am new in programming and I am still learning. İf you help me I will be happy. Thanks.
<script type="text/javascript">
$('#PhoneNumber').bind('keypress', function (e) {
if (e.keyCode == 13) {
var test = $('#PhoneNumber').val().length;
if (test == 0) {
alert('At Least');
/* $('a.login-window').one(function () {
var loginBox = $(this).attr('href');
//Fade in the Popup and add close button
$(loginBox2).fadeIn(300);
//Set the center alignment padding + border
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top': -popMargTop,
'margin-left': -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function () {
$('#mask , .login-popup').fadeOut(300, function () {
$('#mask').remove();
});
return false;
});*/
}
else
{
alert('At Least');
$("#PhoneNumber").val("");
$('#PhoneNumber').focus();
}
}
});
</script>
Always put your jquery code into:
$(document).ready(function() {
//Your code
});
This makes sure that the DOM is loaded when you attach event handlers to elements.
And for me it looks like the return false of your one callback function is killing the fadeIn before it's finished.
You could add the event object e as a parameter of the function and then use e.stopPropagation() and e.preventDefault() instead of return false; like that:
$('a.login-window').one(function (e) {
e.stopPropagation();
e.preventDefault();
//Your code
});

Using arrow keys with jQuery scrollTo

I have successfully implemented the scrollTo jQuery plugin which scrolls to the next div with the class "new" when a link is clicked. However, I would also like to be able to use the arrow keys to scroll up and down to the next/previous divs of the same class.
I have looked all over the internet but have been unable to find out how to do this. I am very new to JS so very simple instructions would be appreciated!
Here is the relevant code:
<script type="text/javascript">
jQuery(function($){
$('<div id="next_arrow"></div>')
.prependTo("body") //append the Next arrow div to the bottom of the document
.click(function(){
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
});
});
</script>
What do I need to add to this to make the arrow keys work?
Thanks,
Ted
You can use the keydown event listener to listen for keypresses. You can use this on <input> fields and the like. Because keydown events bubble up the DOM, you can use it on the document object to catch any keypress on the page:
$(function () {
$(document).keydown(function (evt) {
alert("Key pressed: " + evt.keyCode);
});
});
Each keypress has a code. If you use the code above in your web page, you'll see that the key code for the down arrow is 40. You can solo this out using an if or switch statement in the handler:
jQuery(function () {
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
alert("You pressed down.");
}
});
});
Now you need to bind in the code that actually jumps to the next heading. I recommend abstracting the code out into a function so you can use it for both keypresses and clicks. Here is the function, together with a variant of your original code that uses it:
// Here is the function:
function scrollToNew () {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
// Here is your original code, modified to use the function:
jQuery(function () {
$("#next").click(scrollToNew);
});
Finally, you can add in the keypress code and call the function from there:
function scrollToNew () {
scrollTop = $(window).scrollTop();
$('.new').each(function(i, h2){ // loop through article headings
h2top = $(h2).offset().top; // get article heading top
if (scrollTop < h2top) { // compare if document is below heading
$.scrollTo(h2, 800); // scroll to in .8 of a second
return false; // exit function
}
});
}
jQuery(function () {
$("#next").click(scrollToNew);
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
}
});
});
Update: To scroll upwards, do two things. Change the keydown handler to:
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
scrollToNew(); // scroll to the next new heading instead
} else if (evt.keyCode == 38) { // up arrow
evt.preventDefault();
scrollToLast();
}
}
and write a scrollToLast() function based off of scrollToNew() that finds the last new heading that isn't on the page:
function scrollToLast () {
scrollTop = $(window).scrollTop();
var scrollToThis = null;
// Find the last element with class 'new' that isn't on-screen:
$('.new').each(function(i, h2) {
h2top = $(h2).offset().top;
if (scrollTop > h2top) {
// This one's not on-screen - make a note and keep going:
scrollToThis = h2;
} else {
// This one's on-screen - the last one is the one we want:
return false;
}
});
// If we found an element in the loop above, scroll to it:
if(scrollToThis != null) {
$.scrollTo(scrollToThis, 800);
}
}
Just for giving more idea, working with arrays.
var panel_arr = new Array();
$(document).ready(function(e) {
$('.parallax-panel-wrapper').each(function(i, element){
panel_arr.push( $(this).attr("id") );
});
var current_parallax_panel_no = 0;
$(document).keydown(function (evt) {
if (evt.keyCode == 40) { // down arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
if(current_parallax_panel_no < (panel_arr.length-1)) current_parallax_panel_no++;
scrollByArrowKeys(1);
} else if (evt.keyCode == 38) { // up arrow
evt.preventDefault(); // prevents the usual scrolling behaviour
if(current_parallax_panel_no >= 1) current_parallax_panel_no--;
scrollByArrowKeys(0);
}
});
function scrollByArrowKeys(add_more){
scrollToThis = (($("#" + panel_arr[current_parallax_panel_no]).offset().top) + add_more ; // get element top
$.scrollTo(scrollToThis, 800);
}
});
You need to capture the keypress event and decide which keycode was pressed
$(document).keypress(function(e) {
switch(e.keyCode) {
case 37:
//left arrow pressed
break;
case 39:
//right arrow pressed
break;
}
});

Categories