Added class using javascript not working - javascript

I am adding two classes using javascript on my table, the css for the classes is:
//using less
.fade-table {
background-color: #fff;
opacity: 0.5;
&:hover {
opacity: 1;
}
}
.selected {
opacity: 1;
}
what i am trying to achieve here is that, my table fades at the opacity: 0.5 and the selected cell is applied with the selected class which highlights the selected cell.
The javascript being used is:
$("#pending_states table tr").live("click",function(){
$("#pending_states table").css({width: "140px"});
$("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").addClass("fade-table");
$("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").css({width: "140px"});
$("#pending_states").animate({ marginLeft: "4px"}, 200);
$(this).addClass("selected");
});
However for some reason after adding the fade-table class the script doesn't apply the selected class to the td. The obvious reason that i can think of is that this doesn't represent the td so o also tried $(this).closest("td").addClass("selected");. However this doesn't seem to work either.
Any suggestions on how this might work?

If you want to apply "selected" to the <td> that was clicked on, try:
$("#pending_states table tr").live("click",function(e){
$("#pending_states table").css({width: "140px"});
$("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").addClass("fade-table");
$("#pending_states td:nth-child(1), #pending_states th:nth-child(1)").css({width: "140px"});
$("#pending_states").animate({ marginLeft: "4px"}, 200);
($(e.target).is('td') ? $(e.target) : $(e.target).closest('td')).addClass("selected");
});
(or something less ugly). The idea is to use the event parameter to find the actual target of the click.

You are setting opacity on the wrong element. fade-table is applied to the cell, but selected is applied to the row, so the cell will still be set at 50% opacity.
http://jsfiddle.net/UNgbh/2/

Related

Add & remove classes with fewer lines of code

I'm trying to learn how to shorten my jQuery code. Any suggestions or tips would be awesome:
jQuery(document).ready(function($){
$('#checkout_timeline #timeline-4').click(function() {
if ($('#checkout_timeline #timeline-4').hasClass('active')) {
$('#checkout-payment-container').addClass('cpc-visible');
}
});
$('#checkout_timeline #timeline-1, #checkout_timeline #timeline-2, #checkout_timeline #timeline-3').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
To avoid clutter, please find the working version here:
My JSFiddle Code
I know I can use .show() and .hide() but due to other CSS considerations I want to apply .cpc-visible.
There are a handful of things you can improve here. First, you're over-specifying. Ids are unique. No need to select #checkout_timeline #timeline-4 when just #timeline-4 will do. But why even have ids for each li? You can reference them by number using the :nth-child(n) selector. Or better yet, you've already given them application-specific class names like billing, shipment, and payment. Use those! Let's simplify the original content to:
<ul id="checkout_timeline">
<li class='billing'>Billing</li>
<li class='shipping'>Shipping</li>
<li class='confirm'>Confirm</li>
<li class='payment active'>Payment</li>
</ul>
<div id='checkout-payment-container' class='cpc-visible'>
This is the container to show and hide.
</div>
Notice I left the active class, and indeed further initialized the checkout
div with cpc-visible to mirror the payment-is-active condition. Usually I would keep HTML as simple as possible and put "starting positions" initialization in code. But "in for a penny, in for a pound." If we start with payment active, might as well see that decision through, and start the dependent div in a consistent state.
Now, revised JavaScript:
jQuery(document).ready(function($) {
$('#checkout_timeline li').click(function() {
// make clicked pane active, and the others not
$('#checkout_timeline li').removeClass('active');
$(this).addClass('active');
// show payment container only if payment pane active
var paymentActive = $(this).hasClass('payment');
$('#checkout-payment-container').toggleClass('cpc-visible', paymentActive);
});
});
This code is much less item-specific. It doesn't try to add separate click handlers for different tabs/panes. They all get the same handler, which makes a uniform set of decisions. First, that whichever pane is clicked, make it active and the others not active. It does this by removing all active classes, then putting active on just the currently selected pane. Second, it asks "is the current pane the payment pane?" And it uses the toggleClass API to set the cpc-visible class accordingly. Often such "set class based on a boolean condition" logic is simpler and more reliable than trying to pair appropriate addClass and removeClass calls.
And we're done. Here's a JSFiddle that shows this in action.
Try this : You can user jquery selector with timeline and active class to bind click event handler where you can add required class. Same selector but not having active class to remove class.
This will be useful when you add / remove elements and will be more flexible.
jQuery(document).ready(function($){
$('#checkout_timeline .timeline.active').click(function() {
$('#checkout-payment-container').addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.active)').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
JSFIddle
Here is one of the ways, you can shorten this code by using :not(). Also its better to use elements than to reference and get them via JQuery always.
jQuery(document).ready(function($) {
var showHideContainer = $('#checkout-payment-container');
$('#checkout_timeline .timeline.active').click(function() {
showHideContainer.addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.payment)').click(function() {
showHideContainer.removeClass('cpc-visible');
});
});
try this code its working fine with fiddle
$('.timeline').click(function() {
if ($(this).hasClass('active') && $(this).attr("id") == "timeline-4")
$('#checkout-payment-container').addClass('cpc-visible');
else
$('#checkout-payment-container').removeClass('cpc-visible');
});
This would of been my approach cause you still have to add/remove the active class between each li.
jQuery(document).ready(function($) {
$('ul li').click(function() {
$('ul li.active').removeClass('active');
$(this).closest('li').addClass('active');
k();
});
var k = (function() {
return $('#timeline-4').hasClass('active') ? $('#checkout-payment-container').addClass('cpc-visible') : $('#checkout-payment-container').removeClass('cpc-visible');
});
});
#checkout-payment-container {
float: left;
display: none;
background: red;
color: white;
height: 300px;
width: 305px;
padding: 5px;
}
ul {
list-style: none;
width: 100%;
padding: 0 0 20px 0px;
}
li {
float: left;
padding: 5px 11px;
margin-right: 5px;
background: gray;
color: white;
cursor: pointer;
}
li.active {
background: black;
}
.cpc-visible {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout_timeline">
<li id='timeline-1' class='timeline billing'>Billing</li>
<li id='timeline-2' class='timeline shipping'>Shipping</li>
<li id='timeline-3' class='timeline confirm'>Confirm</li>
<li id='timeline-4' class='timeline payment'>Payment</li>
</ul>
<div id='checkout-payment-container'>
This is the container to show and hide.
</div>
Your code look great, i would have written it the same.
bit sure how much it helps but if you like, you can use inline if like this:
$(document).ready(function(){
$('#B').click(function() { (!$('#B').hasClass('active')) ?
$('#A').addClass('active') : ''; });
$('#C').click(function() { $('#A').removeClass('active'); });
});
Link for a live example:
jsFiddle

What is the best way to show icon/button only when hover on an object ?

I have a cover-image like this
When the user hover on my image, I want to :
show an camera icon on the top left, and
hide it back when the mouse move away.
I have tried
CSS
<style type="text/css">
#cover-img:hover{
opacity: .9;
}
#nav-upload-icon{
top: 10px;
left: 10px;
color: red;
z-index: 1000;
}
</style>
HTML
<img id="cover-img" src="/material/img/profile-menu.png" height="130px">
<i id="nav-upload-icon" class="md md-camera hidden"></i>
JS
$("#cover-img").hover(function() {
$("#nav-upload-icon").removeClass( "hidden" );
});
I couldn't get it to behave what I expected to see.
What is the best way to implement something like that ?
JSFiddle
There is no reason to use JavaScript if that is the actual html code, you can use the next sibling selector with hover.
#cover-img:hover + #nav-upload-icon,
#nav-upload-icon:hover {
visibility: visible;
}
#nav-upload-icon {
visibility : hidden;
}
bind mouseout event to remove add the hidden class again
$("#cover-img").hover(function() {
$("#nav-upload-icon").removeClass("hidden");
});
$("#cover-img").mouseout(function() {
$("#nav-upload-icon").addClass("hidden");
});
Give position absolute to place it over the image
Fiddle
Go for #epascarello solution. It is the best.
The hover accepts two functions:
$("#cover-img").hover(function() {
$("#nav-upload-icon").removeClass("hidden");
}, function() {
$("#nav-upload-icon").addClass("hidden");
});
Fiddle
But obviously the CSS solution is better.
Your almost there. Add a second anonymous function to add the class for mouseleave
$("#cover-img").hover(function() {
$("#nav-upload-icon").removeClass("hidden");
}, function() {
$("#nav-upload-icon").addClass("hidden");
});
According to hover(), you can pass in handlerIn/handlerOut which are synonymous with mouseenter/mouseleave
DEMO
If you don't want to use javascript, wrap a div around the image.
<div class="image-wrap">
<img > <-- your super cool large image
<img class="upload"> <- your super cool icon and stuff absolutely positioned with 0 transparency
</div>
Then in the css you go something like this
div.image-wrap:hover img.upload {
opacity:0.9
}
Don't bother with javascript, it's 2015
This can be achieved without any JS. Using the adjacent selector you can show the icon when #cover-img is hovered on.
#cover-img:hover + img {
opacity: 1;
}
Updated Fiddle

jQuery - how to remove a class from an element with a given delay?

When a user updates a record in the database, I'll modify the record using an AJAX request. Then, I add to the rendered div a class by calling the addClass method. The class I add (let's call the class colored) to the div contains only a background color directive (to highlight the current modified record).
So far so good.
Now I want to remove this class with a fadeOut effect, after 1 second.
I've tried these approaches, but in both cases it's not only removing the class but the whole div.
$("#id1").fadeOut(1000, function() {
$(this).removeClass('colored');
});
or
$("#id1").delay(1000).fadeOut().removeClass('updated_item');
Why is the div removed instead of the class ? Actually, the div is getting a display: none; style - I see this in the console.
fadeOut will fade the entire element out and hide it from the screen. If you want to fade the effects of the class, you can use jQuery UI .removeClass() (which accepts a time duration and fade effect, unlike regular jQuery) or CSS3 transitions.
You can use setTimeout function like this:
setTimeout(
function(){
$("#id1").removeClass('updated_item');
}
,1000 //1 second
)
And if you want to change the color with animation you can just add a transition style in your CSS like this:
.myDiv{
background:red;
transition:background 1s;
-webkit-transition:background 1s;
}
.colored
{
background:blue;
}
I dont know if I got it, is this what you want ?
Fiddle
jQuery('.action').click(function() {
jQuery(this).parent().addClass('highlight');
if ( confirm('Are you sure?') ) {
jQuery(this).parent().fadeOut(1000, function() {
jQuery(this).addClass('remove').removeClass('highlight');
});
} else {
jQuery(this).parent().removeClass('highlight');
}
});
.highlight {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
#1 Click me
</div>
<div>
#2 Click me
</div>
You're applying the fadeOut function to the div itself, not on the class:
//the div, will fadeout after 1000 ms and get the class removed
$("#id1").delay(1000).fadeOut().removeClass('updated_item');
If you want to remove the background-color with a fading effect, you'd have to use something like:
setTimeout(function() {
$('#id1').removeClass('updated_item');
}, 1000)
On the css side, use a transition for the fadeOut effect:
#id1 {
transition: background-color 0.5s ease;
}
.updated_item {
background-color: yellow;
}
Fiddle

How to make a div that appear on hover, stay while its hovered on in jquery or css

I have a div called title, and another one called description.
I have managed to make the div description appear while hovering on title.
here is the fiddle
Now I want to make the div description stay visible while I'm hovering on it (ON THE DESCRIPTION DIV).
Once i remove the hover form the div description, it should hide.
Here is my html
<span class="title">Last</span>
<div class="description">some description</div>
Here is my JS
var cancel = false;
$("div.description").hide();
$(".title").hover(function () {
cancel = (cancel) ? false : true;
if (!cancel) {
$("div.description").hide();
} else if (cancel) {
$("div.description").show();
}
});
And this is the CSS
.title { background: red; }
.description { background: yellow; }
You may not need jQuery to do this.
Given the markup you provided, just use plain CSS and utilize the adjacent sibling combinator, +:
Example Here
.description {
display: none;
}
.title:hover + .description,
.description:hover {
display: block;
}
If you need to use jQuery, you can just include the .description element in your jQuery selector:
Updated Example
$(".title, .description").hover(function () {
// ...
});

jquery setting correct height for content

I've set up a div that stores text with a nice gradient fade at the bottom with a show hide button. I found this tutorial to help me do that, and for the most part i've managed to get it working for my needs.
However, I'm having an issue where when i have a rather long bit of text. When showing the text, it cuts off the bottom of the text. By doing a console.log($("#id).height()); it appears that it's picking up the div's max-height from the CSS rather than the height of the actual content (but i could be wrong).
I've set up a JSFiddle with my example: http://jsfiddle.net/3gnK7/4/ you'll notice that by clicking the Show button on the first part, the last para of the lorem ipsum text is cut off.
This does add a requirement of jqueryUI to get the animation however it works completely
first change your css to
.category_text {
float: left;
position: relative;
overflow: hidden;
margin-bottom: 1em;
max-height: 120px;
}
.cat-height {
max-height: 9999px;
padding-bottom:30px;
}
then change your javascript to use toggleClass like so
$(document).ready(function () {
$(".showbutton").live("click", function (e) {
e.preventDefault();
var buttonid = $(this).attr("id");
buttonid = buttonid.substring(11, buttonid.length);
$("#text_"+buttonid).toggleClass('cat-height','slow');
if($("#showbutton_" + buttonid).text() == 'Show') {
$("#showbutton_" + buttonid).text("Hide");
}
else {
$("#showbutton_" + buttonid).text("Show");
}
return false;
});
});
DEMO
totalHeight += $(this).outerHeight(true);
True argument will include margins, too.

Categories

Resources