Opening and closing navigation - javascript

I have a short JS code that should add and remove a class. The thing is, it adds a class but it never removes it. I can't find the problem. It should add and remove the class by clicking the same button.
$('.hamburger').on('click', function(){
if (!$(this).hasClass('opened')){
$(this).addClass('.opened');
$('.pop').css({'width' : '550px'});
$('.main').css({'margin-right' : '550px'});
}
else{
$(this).removeClass('opened');
$('.pop').css({'width' : '0'});
$('.main').css({'margin-right' : '0'});
}
});

try to use toggleClass method of Jquery it will add or remove class .
$('.hamburger').on('click', function(){
$(this).toggleClass("main");
});

You needn't add the dot to the class string you pass to $(this).addClass so instead it should be:
$(this).addClass('opened');

Remove the "." in $(this).addClass('.opened'); ==> $(this).addClass('opened');
For the style class, you can also use toggleClass (http://api.jquery.com/toggleclass/)

Its because you were adding '.opened' instead of opened.
maybe look at the toggle function to clean up your code. also there's no point refetching the element on each run.
hopefully, this gives you a good idea on how to clean up and reduce repeating yourself.
const pop = $('.pop'),
main = $('.main'),
ham = $('.hamburger');
ham.on('click', toggleHamburger);
function toggleHamburger() {
toggleMainStyles(!ham.hasClass('opened') ? '550px' : 0);
}
function toggleMainStyles(value = 0) {
pop.css({ width: value });
main.css({ marginRight: value });
ham.toggleClass('opened');
}
.hamburger {
color: blue;
}
.opened {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hamburger">ham</div>
<div class="main"></div>

Related

If statement only checks variable value once in javascript

I am trying to understand how javascript (jquery in this case) if statements work. I thought i understood but i don't fully get some things. Please see the code below. Why is it when i click on the element with the class of "cat" that it does not remove the class of "black" and add the class of "red".
$(function() {
var cat = true;
$( ".cat" ).click(function() {
cat = false;
});
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
i know there is probably a very simple answer to this but i'm just learning so any help would be appreciated, thanks in advance.
Toggle the value of cat and put the if block inside the function that you want to bind with the event 'click':
$(".cat").click(function() {
cat = !cat;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
}
});
Edit: Simpler way to do this is to use .toggleClass():
$(".cat").click(function() {
$(this).toggleClass('red black');
});
If you want to check on click, put the if inside the click event. The reason why your solution doesn't work is because you attach a listener to the element, but you immediately do a check. The check doesn't happen every time the user clicks, just once. You must put it in the listener's callback function so it executes every time the element is clicked:
$(function() {
$(".cat").click(function() {
$(".cat").toggleClass("black red");
});
});
How this works is it attaches a click event to .cat and, on click, toggles the classes black and red. This completely gets rid of the checking because that isn't necessary. Just toggle the classes on click. Also, no need to repeat the selector, just use this. Here's a snippet:
$(function() {
$(".cat").click(function() {
$(this).toggleClass("black red");
});
});
.black {
color: black;
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat red">Test</div>
Your code is not removing class black and adding class red because your if(){}else{} code block running when your page is loading. When you are clicking the cat class it is only assigning the value of cat variable to false. since your if else code block is out of your click function that is why it is not executing again. and that is why it is not working. To work your code place your if else code block in the click function like this:
$( ".cat" ).click(function() {
cat = false;
if (cat === true) {
$('.cat').removeClass('red').addClass('black');
} else {
$('.cat').removeClass('black').addClass('red');
};
});

jQuery - update function with deprecated toggle() [duplicate]

This question already has answers here:
Jquery Toggle two function not work in 1.10.1
(7 answers)
Closed 9 years ago.
I would like to update my website to jQuery 1.10 but I use a function with the deprecated toggle().
I remember, I was having a hard time to make this function works in first time, does it exists a function that could replace the toggle() without changing all the code.
I am not a jQuery expert and help would be appreciated.
css:
fieldset.collapsed * {
display: none;
}
fieldset.collapsed h2, fieldset.collapsed {
display: block !important;
}
fieldset.collapsed h2 {
background-image: url(../img/nav-bg.gif);
background-position: bottom left;
color: #999;
}
fieldset.collapsed .collapse-toggle {
background: transparent;
display: inline !important;
}
jquery:
var sPath=window.location.pathname;
(function ($) {
$(document).ready(function () {
function show () { // Show
$(this).text(gettext("Hide"))
.closest("fieldset")
.removeClass("collapsed")
.trigger("show.fieldset", [$(this).attr("id")]);
window.localStorage.setItem($(this).attr("id"), true);
}
function hide () { // Hide
$(this).text(gettext("Show"))
.closest("fieldset")
.addClass("collapsed")
.trigger("hide.fieldset", [$(this).attr("id")]);
window.localStorage.removeItem($(this).attr("id"))
return false;
}
// Add anchor tag for Show/Hide link
$("fieldset.collapse").each(function (i, elem) {
// Don't hide if fields in this fieldset have errors
key = 'fieldsetcollapser' + i + sPath;
if (typeof (window.localStorage) != 'undefined') {
var item = $(elem)
.addClass("collapsed")
.find("h2")
.first()
.append(' (<a id=' +
key +
' " class="collapse-toggle" href="#">' +
gettext("Show") +
'</a>)'
).find('a');
if (window.localStorage.getItem(key)) {
//alert('show')
show.apply(item);
$(item).toggle(hide, show);
}else {
if ($("ul.errorlist").length >0) {
//alert('yo show')
show.apply(item);
$(item).toggle(hide, show);
}else{
$(item).toggle(show, hide);
//alert("hide")
}
}
} else {
throw "window.localStorage, not defined";
}
});
});
EDITED:See how it works here (working with jQuery 1.6)
The reason that the .toggle() function was deprecated was because of confusion just like this!
What's going on is that your code is calling (on an alternating basis) your own internal "hide" and "show" functions. The .toggle(hide,show) call takes care of that for you.
However, inside of your hide() and show() functions, you're not actually hiding or showing anything. What you're doing is adding or removing a class, which may or may not hide or show something.
The solution
The only solution to alternatively call these two functions is to change the 'click' event each time one of those functions is called.
At the bottom of your show() code, you need to add:
$(this).one("click", hide);
At the bottom of your hide() code, you need to add:
$(this).one("click", show);
Finally, you need to replace your calls to .toggle() with these calls:
$(item).one("click", hide); // replaces $(item).toggle(hide,show);
$(item).one("click", show); // replaces $(item).toggle(show,hide);
Why not .is(":visible")?
Quite simply, the class that you are adding/removing is the "collapsed" class. This class does not actually hide the $(item). Because of this the $(this).is(":visible") will always be true!
Clearly, that won't work.
Here is a demonstration that illustrates the point: JSFiddle
Fully in code
For those who like to read code instead of words:
function firstEvent() { // e.g. "hide"
//First event code
$(item).one("click", secondEvent);
}
function secondEvent() { // e.g. "show"
//Second event code
$(item).one("click", firstEvent);
}
$(item).one("click", firstEvent); // replaces $(item).toggle(firstEvent, secondEvent);
I would replace your instances with an if statement
$(item).click(function(){
if ($(this).is(':visible')) {
$(this).hide();
}
else {
$(this).show();
}
});
Here is a demo of my above code working using a p element and an img.
DEMO http://jsfiddle.net/kevinPHPkevin/8TFFx/
You could also do it by using CSS/Jquery
$('p').click(function(){
if ($('img').is(':visible')) {
$('img').css("display","none");
}
else {
$('img').css("display","block");
}
});

Assign two different jquery click events to same item

I have a button on my site that has jquery that changes some css of other elements on click.
I want to assign another function to reverse the css changes when the button is clicked a second time.
$('.mobileitem').click(function(){
$('.bottomfooter').css("bottom","75px");
$('#mobilefoot').css("display", "block");
});
I want to be able to click .mobileitem again and have the css change to bottom:0 display:none for their respective elements.
Each time I click the .mobileitem it should go between the two.
I think it is .toggle() but not sure of the proper syntax or if there is a better way
$('.mobileitem').click(function(){
var bot_val="75px";
var dis_val="block";
if($('.bottomfooter').css("bottom")==bot_val){
bot_val="0px";
}
if($('#mobilefoot').css("display")==dis_val){
dis_val="none";
}
$('.bottomfooter').css("bottom", bot_val);
$('#mobilefoot').css("display", dis_val);
});
This should work!
Try this
function toggleClickEvents(item, click1, click2){
$(item).off('click').on('click', function(){
click1();
toggleClickEvents(item, click2, click1);
});
}
Or just use .toggle() although it is deprecated and possibly removed. (Not sure what the replacement is)
$('.mobileitem').toggle(function(){
$('.bottomfooter').css("bottom","75px");
$('#mobilefoot').css("display", "block");
}, function(){
$('.bottomfooter').css("bottom","0px");
$('#mobilefoot').css("display", "none");
});
Here's a neater, cleaner example using TOGGLE functionality.
It'll work as well. :)
you can write two css classes
.bottom75
{
bottom: 75px;
display: block;
}
.bottom0
{
bottom: 0px;
display: none;
}
On click event
$('.mobileitem').click(function(){
$(this).hasClass('bottom75') ? $(this).addClass('bottom0'): $(this).addClass('bottom75');
});
try this:
$('.mobileitem').click(function(){
$(".bottomfooter, #mobilefoot").toggle(function() {
$('.bottomfooter).css('bottom','75px');
$('#mobilefoot').css('display', 'block');
}, function () {
$('.bottomfooter').css('bottom','0');
$('#mobilefoot').css('display', 'none');
});
});

Hiding a div when the innerHTML is null

I am pretty new to jQuery but I am trying to get a code setup which hides a div when the 'innerHTML' is null. I tried using the code below. But it doesn't work! Where is my fault??
if (($("#php-errors").html).length) {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
One line, and using .show() and .hide() methods:
var hasCont = $("#php-errors").contents().length ? $("#php-errors").show() : $("#php-errors").hide();
Using the ternary operator that says:
(define var) statement ?
action if statement is true :
action if statement is false ;
DEMO JSFIDDLE
A good practice would be to cache your element inside a var, let's call it var $el, and use it like:
var $el = $("#php-errors");
var hasCont = $el.contents().length ? $el.show() : $el.hide();
Much more readable, and
it will save you some micro processing time ;) but it really helps in terms of cross-function reusability (if defined outside the function.)
if ($("#php-errors").html().length) {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
Correction:
($("#php-errors").html).length should be $("#php-errors").html().length
You can clean your code a little like this.
It also uses the innerHTML property as the condition part of the ternary expression. If there's any content, it'll return and set "block", if not, then "none".
$("#php-errors").css("display", function() {
return this.innerHTML ? "block" : "none";
});
http://jsfiddle.net/WKWNc/2/
update:
If this only runs when the page loads, you could initially have it set to "block", and then do this.
$("#php-errors:empty").hide();
http://jsfiddle.net/WKWNc/1/
Or the opposite, have it set to "none", and show it if not empty.
$("#php-errors:not(:empty)").show();
http://jsfiddle.net/WKWNc/
Just to add the css way that will not require javascript in case someone else needs it:
.php-errors:empty { display: none; }
Will Match:
<div class="php-errors"></div>
<div class="php-errors"><!-- test --></div>
Will Not Match:
<div class="php-errors"> </div>
<div class="php-errors">
<!-- test -->
</div>
<div class="php-errors">
</div>
Source: https://css-tricks.com/almanac/selectors/e/empty/
For your case, it seems you just want:
$("#php-errors").toggle();
I can see no case where you want to set the display to either block or none if none is already set.
Are you sure your logic isn't redundant?
I think u missed compare , try this
if ($("#php-errors").html() == "") {
$("#php-errors").css("display", "block");
}
else {
$("#php-errors").css("display", "none");
}
I would do something like this:
var $php_errors = $("#php-errors");
if ($php_errors.is(":empty")) {
$php_errors.hide()
}
else {
$php_errors.show();
}
hope it helps

On second click; jQuery

<div class="example">
Test
</div>
$('.example').click(function(){
$(this).css('color','red');
});
When the code above get's clicked, it will apply the .css. Now what I need is for another bit of code (let's say $(this).css('color','blue');) to be applied, replacing the previous code when .example gets clicked a second time.
I've searched for this and askers seem to only need .show/.hide events which can be substituted with .toggle, which is obviously not the case here.
Since you may have many instances of class example, simply maintaining a state using a single variable is not feasible, what you can do is to maintain the state of each instance of example within itself:
Define two css classes
.example { background:blue }
.example.red { background:red }
Then your click method:
$('.example').click(function(){
$(this).toggleClass('red');
});
If you prefer not to define new css classes, you can use data(), to make sure that the state is exclusive within each .example, this is useful if you have many instances of .example
$('.example').click(function() {
var color = $(this).data('color');
if(color != 'blue') {
$(this).css('color', 'blue');
$(this).data('color', 'blue');
} else {
$(this).css('color', 'red');
$(this).data('color', 'red');
}
});
http://api.jquery.com/data/
Something like this would work to toggle between 2 colours (or styles).
$('.example').click(function(){
if($(this).css('color') == "red")
{
$(this).css('color','blue');
}
else
{
$(this).css('color','red');
}
});
<div class="example">
Test
</div>
just maintain a bool and you are done..
var isRed=false;
$('.example').click(function(){
if(isRed)
{
$(this).css('color','blue');
isRed=false;
}
else
{
$(this).css('color','red');
isRed=true;
}
});
Use addClass and removeClass
.blueColor
{
background-color: blue;
}
.redColor
{
background-color: red;
}
And use in your javascript the addClass and removeClass functions:
<script>
$(document).ready(function(){
$(".example").keypress(function() {
if($(".example").val().length > 0)
{
$(".example").addClass("redColor");
}
else {
if($(".example").val().length == 0)
{
$(".example").addClass("blueColor");
$(".example").removeClass("redColor");
}
}
});
});
</script>
I guess you need something more generic about click event exactly so I'd suggest you to use data method to leave the flags
$('.example').click(function() {
if (!$(this).data("custom-even")) {
// odd execution
$(this).data("custom-even", true)
} else {
// even execution
$(this).data("custom-even", false)
}
});​
$('.example').click(function(){
var theExample = $(this);
if(theExample.hasClass("clicked")){
theExample.css('color','blue').removeClass("clicked");
}else{
theExample.css('color','red').addClass("clicked");
}
});
http://jsfiddle.net/SnDgh/
Hiya Try this with toggle :)) http://jsfiddle.net/FVXAZ/
SO you can use toggle with your css and every second click will have the vice-a-versa affect. :)
Code
$(function() {
$('.example').toggle(function() {
$(this).css('color','red');
}, function() {
$(this).css('color','blue');
});
});
Have a nice man man, cheers!
Try this:
$('.example').click(function(){
if($('.example').data('isAlreadyClicked')=='true')
{
$(this).css('color','blue');
$('.example').data('isAlreadyClicked','false')
}
else
{
$(this).css('color','red');
$('.example').data('isAlreadyClicked','true')
}
});
Use the one method to handle one-time event binding is a good choice, however this solution will stop all events binded after this code, it may cause inconsistency.
$('.example')
.one('click', function(e) {
e.stopImmediagePropagation();
})
.on('click', function() {
$(this).css('color', blue');
});
Lot of answers all defining a single solution.
Basically, there are two ways that you should use. The other ways mentionned are either unperformant or unsemantic (using data for this kind of solution is overkill). Here are the two ways you may use:
// Toggle a class 'red' defined in your stylesheet
$('.example').on('click', function() {
$(this).toggleClass('red')
})
// Toggle the color with an "if" check
$('.example').on('click', function() {
if (this.style.color === 'red') { // using jQuery is not required
this.style.color === 'blue'
}
else {
this.style.color === 'red'
}
})
You can write:
$('#id').toggle(function() {
$('.css').css('color','red');}
,function() { /////////the second click
$('.css').css('color','blue');}
);

Categories