Animate element with specific class and CSS properties - javascript

I read Jquery: How to check if the element has certain css class/style and have got this working -
if ($(".box").css('display') == 'block')
{
console.log("message 2 - Div with box class exists and css Block exists")
}
I read how to create jquery slide left and right toggle and got this working -
$(".box").animate({width: "toggle"});
I can't seem to combine the two above together though. These two attempts failed -
// ($(".box").css('display') == 'block').animate({width: "toggle"});
// ($(".box").css('display') == 'block').animate({width: "toggle"});
var datebox = ($(".box").css('display') == 'block')
datebox.animate({width: "toggle"})
datebox.animate({width: "toggle"})
Update 1
I tried Cucunber's suggestion and got this error -
Uncaught TypeError: ".box".each is not a function
Update 2
I solved the problem highlighted in Update 1 by adding $ to ('.box'), Cucunber updated his answer below based on the issue I faced.
Update 3
I tinkered with Cucunber's solution and eventually solved my problem with this code.
$(".box" ).each(function( index ) {
if ($(this).css('display') == 'block' ) {
console.log( index + ": " + $( this ) );
}
})

The sentence '$('.box').css('display') == 'block' returns boolean statement. If you know, .animate method should be used with the html element (selector). Try to use something like this:
'$('.box').css('display') == 'block' && $('.box').animate({width: 'toggle'})
combine it with '.each()' and the final result will be:
$('.box').each(function(){ $(this).css('display') == 'block' && $(this).animate({width: 'toggle'}) })

Related

JavaScript toggle class on current element

Just want to understand a principle of JavaScript, I'm a bit new to this.
I'm adding some styling to some element which are slides which I'm scrolling through.
The "current" div have a transform: none applied, the two others get styled depending on where I am on the slider.
I'm using this code which is working fine.
el.style.transform = i === e.current ? 'none' : i > e.current ? 'translateX(100%)' : 'translateX(-100%)'
My question is how do I add / toggle a class to the current el, and remove it back when it's not the current anymore.
I've tried some couple options using the same principle but can't find the right way to achieve it.
el.classList = i === e.current.toggle('classname') : i > ? e.current.toggle('classname')
el.classList.toggle() = i === e.current ? 'active' : i > e.current ? 'prev' : 'next'
Can somebody give me a heads up on how to achieve what i want to do? I've tried to go through some others post on Stack Overflow and to look on element.classList docs everywhere i could find it, but I'm stuck at this point and JS knowledge is not my strong point.
Thanks!
toggle takes the class name e.g. el.classList.toggle('classname'). You don't pass a variable to a function like this el.classList.toggle() = 'classname'. But you might be better off calling add or remove depending on if the item is the current one since you also need to ensure the other classes aren't still there.
el.classList[i === e.current ? 'add' : 'remove']('active');
However since you also want prev and next probably best not to try and be too clever with ternaries and make it readable:
if (i > e.current) {
el.classList.remove('current', 'prev');
el.classList.add('next');
} else if (i < e.current) {
el.classList.remove('current', 'next');
el.classList.add('prev');
} else {
el.classList.remove('prev', 'next');
el.classList.add('current');
}
If you aren't worried about overwriting other classes you could simplify this using className as it overwrites any existing classes:
if (i > e.current) {
el.className = 'next';
} else if (i < e.current) {
el.className = 'prev';
} else {
el.className = 'current';
}

For loop with eval not working

My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});

Uncaught ReferenceError: t is not defined

have a small problem in my function below .
i constantly getting this error : Uncaught ReferenceError: t is not defined .
trying to add this piece of code in my project that is related to wordpress menu.
here it is
t(function() {
var e = t("#categories_navigation"),
i = "click" == e.data("action") ? "click" : "mouseenter mouseleave",
a = t("#categories_navigation_toggle");
"click" == i && e.find("> ul > li:first-child").addClass("active"), a.on(i, function(a) {
"click" == i && a.preventDefault(), t(this).toggleClass("opened"), e.toggleClass("opened")
}), "click" == i && t(document).mouseup(function(t) {
a.is(t.target) || e.is(t.target) || 0 !== e.has(t.target).length || !e.hasClass("opened") || (e.removeClass("opened"), a.removeClass("opened"))
}), e.find(" > ul > li > a").on(i, function(a) {
"click" == i && a.preventDefault();
var n = t(this).parent(),
s = n.find(" > ul");
t(" > ul > li > ul", e).css({
visibility: "hidden",
opacity: "0"
}), s.css({
visibility: "visible",
opacity: "1"
}), "click" == i && (t(" > ul > li", e).removeClass("active"), n.addClass("active"))
});
});
and this is my html codes
<div class="top-nav col">
<?php _e(' Categories Menu '); ?>
<nav class="categories-menu-navigation" id="categories_navigation" data-action="click" role="navigation">
<ul></ul>
</nav>
</div>
i should add that jquery file is attached to the page above all other js files .
thanks in advance .
Based on the functions that you are calling with t I would guess that you are copy-pasting code from somewhere else. In the snippet you gave us, you are referencing a variable called t. The error message you are getting is because in your code you did not define what t is.
From looking at what you posted, my best guess is that t is supposed to be the jQuery variable, but that's traditionally this symbol: $.
There is another issue as well. The code after a = t("#categories_navigation_toggle"); seems to be related to operating a menu like you said, but the syntax is quite wrong for a number of reasons. I think it'd be easier to help you phrase your question better than to try and fix your code without any additional context.
Improving your question
If you did copy-paste code from somewhere, could you link to it so we can see the whole thing? I don't think you have the entire snippet posted in your question.
Also, please explain what you are trying to do with this code. Giving us details about what you're trying to do will be more helpful to us than just saying it doesn't work :)

Loop Toggle for different ID Element

I have this following script to toggle (show and hide):
function btnClass1(where, pval, nval){
var x=$("#btn1-Bln ").val();
if (x == 'Show '){
where.title='Show ';
}
else{
where.title='Hide ';
}
where.value=(where.value == nval) ? pval : nval;
container=document.getElementById("containerXd");
container.style.display=(container.style.display == 'inline-block') ? 'none' : 'inline-block';
container.style.visibility=(container.style.visibility == 'visible') ? 'hidden' : 'visible'
;
I have many IDs to toggle, say, it's about 24 different IDs.
When I use the code it works fine, I just change #btnClass1 to #btnClass2 and 3, etc as well as #btn1-Bln, and containerXd.
But, I feel it's not efficient to build every IDs with new block of the script (again and again).
In this case, I need a simple script to represent all IDs in a web page.
Do you have other best suggestion for me, please
You just need to add two new params to your function for the buttonSelector and the containerSelector. In your example, you would pass in "#btn1-Bln" and "containerXd" for these new params, respectively. Then, use these new variables rather than the hard-coded strings in your function body. This will allow you to use your single existing function with any buttons and containers.

A question about a standard way to hide a div in Javascript and jQuery

I'm still relatively new to javascript and jQuery and was just wondering this.
Suppose I have this HTML snippet:
<p id="disclaimer">
Disclaimer! </p>
<input type="button" id="hideButton" value="hide" />
I could hide the div in the following ways:
$(document).ready(function() {
$('#hideButton').click(function() {
if ($('#disclaimer').css('display') == 'none') {
$('#disclaimer').show();
$('#hideButton').val('hide');
} else {
$('#disclaimer').hide();
$('#hideButton').val('unhide');
}
})
});
OR
$(document).ready(function() {
$('#hideButton').click(function() {
if ($('#disclaimer').is(':visible')) {
$('#disclaimer').hide();
$('#hideButton').val('unhide');
} else {
$('#disclaimer').show();
$('#hideButton').val('hide');
}
})
});
My question is: Is there a preferred method of hiding the div or is it just a matter of personal preference?
i'd write that like this
$(function() {
$('#hideButton').click(function() {
$('#disclaimer').toggle();
$(this).val(
$('#disclaimer').is(":visible") ?
'hide' : 'unhide'
);
})
})
or even
$(function() {
$('#hideButton').click(function() {
$(this).val(
$('#disclaimer').toggle().is(":visible") ?
'hide' : 'unhide'
)
})
})
in response to the comment, here some points why i think this code is better
$(...) looks nicer than document.ready
toggle() without a param is better than "if is visible then hide else show" - don't ask, tell.
always use $(this) to refer to the object itself in an event handler
use chaining when it doesn't hurt readability
Yes, you could use the .toggle(showOrHide) variant:
$(document).ready(function() {
$('#hideButton').click(function() {
var $disclaimer = $('#disclaimer'),
isVisible = $disclaimer.is(':visible');
$disclaimer.toggle(!isVisible);
$('#hideButton').val(isVisible ? 'unhide' : 'hide');
});
});
There is no point in querying the element's style to find out if it's visible; you can retain its state programmatically:
var isVisible = true,
disclaimer = $('#disclaimer'),
hideButton = $('#hideButton');
hideButton.click(function(){
disclaimer[isVisible ? 'hide' : 'show']();
hideButton.val(isVisible ? 'unhide' : 'hide');
isVisible = !isVisible;
});
I would do the actual hiding exactly like user187291 wrote.
But for your questions, I would suggest using the ":visible" selector since there are more ways to hide an element other than changing its display css attribute.
From the jQuery specification:
Elements can be considered hidden for several reasons:
* They have a CSS display value of none.
* They are form elements with type="hidden".
* Their width and height are explicitly set to 0.
* An ancestor element is hidden, so the element is not shown on
the page.
A certain animation may reach the state of having the width and height set explicitly to 0 and not change the display attribute.

Categories