My name is Adam, I'm new to Stack Exchange, but have found this site very useful for many past problems I have had.
I'm having a problem with a jquery function and thought I'd seek advice here. I have a pretty decent knowledge of html & css, a little of php, but virtually none of javascript or jquery.
I'm currently working on a site that uses specific html tags to enable dynamic content as php isn't permitted. Javascript is however so I've been looking it. I don't have a live example to show you here as I can only preview the design from within my account, however I have pasted the script below.
I wanted to create a responsive design, fluid down to mobile. Following recent design trends, I wanted to create 'Slide in/out' style menus from the side of the screen (think Facebook Mobile, Dolphin Browser). After viewing some examples, I wrote a function which altered the CSS, moving the main div#site template to the right, revealing the left menu. Everything was ok and it worked fine.
Today I decided it would be nice to have 2 slide out menus, one on the left, the other, on the right.
I added to the function what I thought was going to work, and it sort of does.
I have a button (with class .open-sidebar-right) to slide the main site (div#site) to the left, revealing the right hand menu. I can then click either the same button or the div#site to close the menu.
The problem occurs when I click on the left button. The left menu opens and closes absolutely perfectly, however it renders the right button totally useless and doesn't function at all.
I've tried writing it as two separate functions, using one variable for both menus with different values, and it always renders the right button useless after using the left button.
As I mentioned earlier, I have virtually no knowledge of Javascript or jQuery, so it's probably poorly coded, but I can't understand why this wouldn't work.
If anyone has any advice or suggestions I would really appreciate it.
Thanks in advance, Adam.
jQuery(function () {
var sidebarleft;
var sidebarright;
// ------------
// Left sidebar
jQuery(".open-sidebar-left").click(function () {
if (!sidebarleft) {
jQuery("#site").css({
'left':'50%',
});
sidebarleft = true;
return false;
} else {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
}
});
// ------------
// Right sidebar
jQuery(".open-sidebar-right").click(function () {
if (!sidebarright) {
jQuery("#site").css({
'right':'50%',
});
sidebarright = true;
return false;
} else {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
// ----------------------------------
// Close sidebars by clicking on site
jQuery("#site").click(function () {
if (sidebarleft) {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
} else if (sidebarright) {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
});
Adam,
#zgood says your code is good, but I thought I'd point out a few errors and make some suggestions which may solve your problem:
$(document).ready(function(){ // in the jQuery doc, they don't suggest you use $(<func>)
var sidebarleft = false, // sidebarleft and sidebarright has to be equal to something
sidebarright = false; // either true or false (I would use false since you're testing false in your conditional
$(".open-sidebar-left").click(function() {
if( !sidebarleft ) {
$("#site").css({
left: '50%' // remove the comma, and do not put quotes around single-word identifiers
});
sidebarleft = true;
return false;
} else {
$("#site").css({
left: '0'
});
sidebarleft = false;
return false;
}
});
$(".open-sidebar-right").click(function() {
if( !sidebarright ) {
$("#site").css({
right: '50%' // remove the comma, and do not put quotes around single-word identifiers
});
sidebarright = true;
return false;
} else {
$("#site").css({
right: '0'
});
sidebarright = false;
return false;
}
});
});
So as you can see in the comments in the code above,
jQuery says it's valid, but not suggested that you use jQuery(function(){}); so query the document element then test for ready, then call a function
sidebarright and sidebarleft were undefined (neither true or false) so your
if statements don't make sense.
In the css() declaration, you shouldn't put a comma on the last element. Only put commas if there are more than one element.
I would also suggest using animate() instead of css(), and also (if you're using Chrome) use the inspector and (if you're using Firefox) use FireBug to test for any errors in your javascript code. Hope this helps.
Your code is right, the problem seems to be a CSS issue.
When you click your left button your click event is adding an inline style to your #site div like so:
<div id="site" style="left:50%;">
Then when you click your right button your code appends the new style to your #site div like so:
<div id="site" style="left: 0%; right: 50%;">
See the problem?
To fix this you must do two things. Since you didn't post your CSS, I don't know how you have your #site styled, but remove any left or right style from your #site style declaration.
Next update your jQuery code to remove any previous inline styles like so:
// ------------
// Left sidebar
jQuery(".open-sidebar-left").click(function () {
jQuery("#site").removeAttr('style');
if (!sidebarleft) {
jQuery("#site").css({
'left':'50%',
});
sidebarleft = true;
return false;
} else {
jQuery("#site").css({
'left':'0%',
});
sidebarleft = false;
return false;
}
});
AND
jQuery(".open-sidebar-right").click(function () {
jQuery("#site").removeAttr('style');
if (!sidebarright) {
jQuery("#site").css({
'right':'50%',
});
sidebarright = true;
return false;
} else {
jQuery("#site").css({
'right':'0%',
});
sidebarright = false;
return false;
}
});
removeAttr is your friend here. Also you may want to use an animate instead of just changing the css values, but thats your call
jQuery .animate()
Related
I have a cookie warning banner on my site that I want to show for users who have not seen it already (check for cookieInformation cookie and if no, show the banner). The issue is that this used to work with a window.onload function, however recently the window.onload never fires. If I use a document.ready, the banner flashes at the top of the screen before sticking to the bottom where it's supposed to be.
I would set a timeout for the function, however, if this is a foundation loading issue, the flash will still occur on slow loading.
Is there a foundation callback function like foundation.ready that I can use to invoke this function?
.container#cookieTin(data-sticky-container)
.cookiebanner.is-hidden.sticky(in-view="$inview == false ? cookieAccept() : '' ", data-sticky='', data-stick-to="bottom", data-options="stickyOn: small;", data-margin-bottom="0", data-closable )
.small-12.medium-6.columns
strong !{ __("cookie.line_1")}
br
span !{ __("cookie.line_2")}
.small-12.medium-6.columns
a.cookieButton.button !{ __("cookie.line_3")}
button.close-button.cookieButton(aria-label='Close alert', type='button', data-close)
span(aria-hidden='true') ×
The JS:
function showCookieBanner() {
$('.cookiebanner').removeClass("is-hidden");
}
$(document).ready(function () {
$(".cookieButton").click(function () {
closePopup();
});
var closePopup = function () {
$('.cookiebanner').css("display", "none");
createCookie('cookieInformation', 'seen', '15');
return false;
}
if (getCookie('cookieInformation') == null) {
showCookieBanner();
}
});
I've tried adding a .no-js class to no avail as well as eventListeners.
I'm trying add a JS code to my templates but I'm getting that security error:
A potential security issue was found in the template. Please review your changes or contact the MyBB Group for support.
Code:
//Start navbar toggle fix top bottom
$(document).on('click', '.toggle_fixing', function(e) {
e.preventDefault();
if ($('#main_navbar').hasClass('navbar-fixed-top')) {
$('#main_navbar').toggleClass('navbar-fixed-bottom navbar-fixed-top');
$(this).children('i').toggleClass('fa-chevron-down fa-chevron-up');
} else {
$('#main_navbar').toggleClass('navbar-fixed-bottom');
$(this).children('i').toggleClass('fa-chevron-down fa-chevron-up');
if ($('#main_navbar').parent('div').hasClass('container')) $('#main_navbar').children('div').addClass('container').removeClass('container-fluid');
else if ($('#main_navbar').parent('div').hasClass('container-fluid')) $('#main_navbar').children('div').addClass('container-fluid').removeClass('container');
FixMegaNavbar(navHeight);
}
if ($('#main_navbar').hasClass('navbar-fixed-top')) {$('body').css({'margin-top': $('#main_navbar').height()+'px', 'margin-bottom': ''});}
else if ($('#main_navbar').hasClass('navbar-fixed-bottom')) {$('body').css({'margin-bottom': $('#main_navbar').height()+'px', 'margin-top': ''});}
})
//End navbar toggle fix top bottom
//Start Fix MegaNavbar on scroll page
var navHeight = $('#main_navbar').offset().top;
FixMegaNavbar(navHeight);
$(window).bind('scroll', function() {FixMegaNavbar(navHeight);});
function FixMegaNavbar(navHeight) {
if (!$('#main_navbar').hasClass('navbar-fixed-bottom')) {
if ($(window).scrollTop() > navHeight) {
$('#main_navbar').addClass('navbar-fixed-top')
$('body').css({'margin-top': $('#main_navbar').height()+'px'});
if ($('#main_navbar').parent('div').hasClass('container')) $('#main_navbar').children('div').addClass('container').removeClass('container-fluid');
else if ($('#main_navbar').parent('div').hasClass('container-fluid')) $('#main_navbar').children('div').addClass('container-fluid').removeClass('container');
}
else {
$('#main_navbar').removeClass('navbar-fixed-top');
$('#main_navbar').children('div').addClass('container-fluid').removeClass('container');
$('body').css({'margin-top': ''});
}
}
}
//End Fix MegaNavbar on scroll page
//Next code used to prevent unexpected menu close when using some components (like accordion, tabs, forms, etc), please add the next JavaScript to your page
$( window ).load(function() {
$(document).on('click', '.navbar .dropdown-menu', function(e) {e.stopPropagation();});
});
How can I fix this error?
Taking a shot in the dark here, but it may be MyBB disagreeing with how you have your code formatted.
when it contains stuff like this: {$('body').css, it may be confusing it as a template variable; eg. {$header}.
Try formatting your code in another way, so there's no brackets right next to dollar signs.
Alternatively, it might be worth keeping js out of the templates and keeping it in a js file.
Hello I have been boggling my mind over and over again trying to simplify this java Script Code.
I am fairly new to JavaScript and I do not know where else to turn.
I am making a navigation that when I click on a button it will animate to transform:translateX(0); from transform:translateX(-98%); as a class.
I am also making it if you hover over the div .main-navigation it will slide back and forth accordingly. I have it where the mouseover will slide the navigation if its open to the close state but I cannot do so when it is closed to open. I am also trying to make it if the .home is active then the hover will not open or close the .home just the menu.
Any suggestions?
$(function(){
var navToggle = document.querySelectorAll('.nav-toggle');
var mainMenu = document.querySelectorAll('.main-navigation');
$(navToggle).on('click', function(){
if ($(mainMenu).hasClass('close')){
$(mainMenu).removeClass('close');
$(mainMenu).addClass('open');
}else{
$(mainMenu).addClass('close');
$(mainMenu).removeClass('open');
};
$('.home').toggleClass('hide, toggleAnimate');
$('.contentWrap').toggleClass('open');
});
$(mainMenu).on('mouseenter', function(){
if ($(mainMenu).hasClass('close')){
$(mainMenu).removeClass('close');
$(mainMenu).addClass('open');
}
if ($(mainMenu).hasClass('open')){
$(mainMenu).removeClass('open');
$(mainMenu).addClass('close');
};
});
});
Sorry I created a Code Pen to show you a very close example of what I am trying to do and the behavior that is happening.
My CodePen Example
Never mind I figured it out, I went with JQuery and was able to achieve my goal. I ended up changing it to this.
$(function(){
homeAnimate();
menuAnimate();
menuAnimate2();
autoAnimateEnter();
autoAnimateExit();
function homeAnimate(){
$('.nav-toggle').click(function () {
$('.home').toggleClass('hide, toggleAnimate');
$('.contentWrap').toggleClass('open');
});
}
function menuAnimate(){
$('.nav-toggle').click(function () {
if ($('.main-navigation').hasClass('close')) {
$('.main-navigation').addClass('close');
$('.main-navigation').toggleClass('open');
}
if ($('.main-navigation').hasClass('open')) {
$('.main-navigation').toggleClass('close');
$('.main-navigation').toggleClass('open');
}
});
}
function menuAnimate2(){
$('.nav-toggle-menu').click(function () {
if ($('.main-navigation').hasClass('open')) {
} else {
$('.main-navigation').addClass('open');
$('.main-navigation').removeClass('close');
}
$('.home').toggleClass('hide, toggleAnimate');
$('.contentWrap').toggleClass('open');
});
}
function autoAnimateEnter(){
$('.main-navigation').mouseenter(function () {
if ($('.main-navigation').hasClass('close')) {
$('.main-navigation').removeClass('close');
$('.main-navigation').addClass('open');
} else {
// DO NOTHING
}
});
}
function autoAnimateExit(){
$('.main-navigation').mouseleave(function () {
if ($('.home').hasClass('toggleAnimate')) {
// DO NOTHING
} else {
$('.main-navigation').removeClass('open');
$('.main-navigation').addClass('close');
}
});
}
});
I'm not sure if this is the cleanest way in order to achieve my goal but it works and I'm happy.
Here is my code if anyone wants to check it out.
Code
I'm somewhat new to Javascript. I'm trying to make it so that clicking on an image on one page takes you to a new page and shows a specific div on that new page, so I used sessionStorage to remember and booleans to keep track of which image is being clicked. Right now, the code always executes the first if statement, regardless of which image is clicked. This code works fine in normal java so I can't figure out why my if statements are being ignored in javascript. I also tried adding an 'else' at the end, and tried ===. Here's my javscript, and thank you!
sessionStorage.clickedLeft;
sessionStorage.clickedMiddle;
sessionStorage.clickedRight;
function openedProjectFromGallery() {
if(sessionStorage.clickedLeft) {
$(".left-project-pop-up").show();
} else if (sessionStorage.clickedMiddle) {
$(".middle-project-pop-up").show();
} else if (sessionStorage.clickedRight) {
$(".right-project-pop-up").show();
}
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
}
$("document").ready(function () {
$(".pop-up .x-button").click(function(){
$(".pop-up").hide();
});
$(".project-description .x-button").click(function(){
$(".project-pop-up").hide();
});
$(".left-project-thumb img").on("click", ".left-project-thumb img", function(){
sessionStorage.clickedLeft = true;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-left-project img").click(function(){
$(".left-project-pop-up").show(1000);
});
$(".middle-project-thumb img").on("click", ".middle-project-thumb img", (function(){
sessionStorage.clickedMiddle = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-middle-project img").click(function(){
$(".middle-project-pop-up").show(1000);
});
$(".right-project-thumb img").on("click", ".right-project-thumb img", (function(){
sessionStorage.clickedRight = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
openedProjectFromGallery();
});
$(".profile-right-project img").click(function(){
$(".right-project-pop-up").show(1000);
});
});
You are defining function openedProjectFromGallery() with in document.ready . Define it outside document.ready and also give your three booleans some initial value at the top of your code if not initialized with some value or they are empty. I hope this would help.
It is not really answer to your orginal question,as the main issue with your code is, as #njzk2 says, that openProjectFromGallery only being called once, and not on each event, however I wanted to put my two coins on how this code could look like.
This is good example where custom events should be used
$(document).on('showPopup', function( e, popup ) {
$('.'+popup + '-project-pop-up').show()
})
$(document).on('hidePopup', function( e ) {
$('.popup').hide()
})
$('.left-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['left'])
})
$('.right-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['right'])
})
I think you get an idea.
On the other hand, it always nice to use event delegation with a lot of similar events as well as dom data.
<div class='popup' data-popup='left'>
<img />
</div>
$(document).on('click','.popup', function( e ) {
$(document).trigger('showPopup', [$(this).data('popup')])
})
From what I can see openedProjectFromGallery is only getting called on document load.
Add a call to it into each of the event handling functions or use jQuery's delegate function to assign event handling to each image.
I'm not the best when it comes to JavaScript, and stuck with finding a solution. I have seen similar questions asked here, but when I try to implement it in my case it either breaks the menu or just makes no difference.
I'm trying to get a menu (which opens on a click), to close not only with a repeated click on parent menu tab, but with a click outside the menu, i.e., anywhere.
My code is:
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.className= 'updates_pulldown_active';
showNotifications();
} else {
element.className='updates_pulldown';
}
}
This snippet is in the middle of a lot more JavaScript and this is the default working version. The click from user changes the class name of the menu container which determines if it's displayed or not. From another post on here, I tried implementing the following to no avail to try and allow the click off to alter the class name as well:
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.className= 'updates_pulldown_active';
showNotifications();
} else {
element.className='updates_pulldown';
}
ev.stopPropagation();
$(document).one('click', function() {
element.className='updates_pulldown';
});
}
Any advice on tackling this? I'd like to learn more JavaScript as I seem to be working with it more and more.
I hope you are still looking for a solution. Here's a working demo of this http://jsfiddle.net/sU9ZJ/6/
(function(win, doc) {
var lis = $('#menu>ul>li>a').on('click', function(e) {
e.preventDefault();
var a = $(this);
var li = $(this).parent();
function close(dev) {
if (!(dev && li.has(dev.target)[0])) {
li.addClass('inactive').removeClass('active');
doc.off('click', close);
a.trigger('close');
}
}
function open(dev) {
li.addClass('active');
doc.on('click', close);
a.trigger('open');
}
if (li.hasClass('active')) { close() }
else { open(); }
})
})(this, $(document))
I have also added a couple of events that you can use when it opens or closes
$('#menu>ul>li>a').on('open', function(e) {
console.log('menu open', this)
}).on('close', function(e) {
console.log('menu closed', this)
})
Sorry, this depends on jQuery. too lazy to write a native version :). Also this is not tested in IE, but shouldn't be too hard to make it work on those if it doesn't.