Jquery animate backgroundColor not working - javascript

I'm trying to have a background color fade in (and then eventually I'll want it to fade back out) when you click a button. I can get the background to change color with this:
$("#" + lblqty).css("background","#e9f1ff");
But when I try to use animate (like below), it doesn't work. Nothing happens and I don't even get a javascript error:
$("#" + lblqty).animate({ backgroundColor: "#e9f1ff"}, 800);
I put the code in JSFiddle so you can see it in action. What should happen is when you click on "item" or check the checkbox, a div should appear that shows "Quantity 1" and a + and - sign. When you click the + sign, it should increase the quantity by 1 and the background should change color. Here's the link: http://jsfiddle.net/ew52wyLm/1/
$(".calccheckbox").change(function() {
var checkid = $(this).attr("id");
var qtyid = "qty_" + checkid;
var lblqty = "qtylbl_" + checkid;
var aic = "aic_" + checkid;
if (this.checked) {
$(this).attr("value", checkid + "_1");
$("#" + qtyid).html("1");
$("#" + lblqty).show(300);
// $("#" + aic).css("background","#b6d1ff");
// $("#" + lblqty).css("background","#e9f1ff");
} else {
$(this).attr("value", checkid);
$("#" + qtyid).html("");
$("#" + lblqty).hide(300);
}
});
$(".calcaddbutton, .calcremovebutton").click(function(event) {
var button = $(this);
var checkid = $(this).attr("id");
checkid = checkid.slice(3);
var qtyid = "qty_" + checkid;
var qty = $("#" + qtyid).html();
var aic = "aic_" + checkid;
var lblqty = "qtylbl_" + checkid;
if (button.hasClass("calcaddbutton")) {
if (qty > 49) {
alert("You may only add 50 of each item");
} else {
qty++;
$("#" + qtyid).html(qty);
$("#" + checkid).attr("value", checkid + "_" + qty);
// $("#" + lblqty).css("background","#e9f1ff");
$("#" + lblqty).animate({
backgroundColor: "#e9f1ff"
}, 800);
}
}
if (button.hasClass("calcremovebutton")) {
if (qty < 2) {
$("#" + qtyid).html("");
$("#" + checkid).attr("value", checkid);
var lblqty = "qtylbl_" + checkid;
$("#" + lblqty).hide(300);
$("#" + checkid).attr("checked", false);
} else {
qty--;
$("#" + qtyid).html(qty);
$("#" + checkid).attr("value", checkid + "_" + qty);
}
}
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="additemcontainer">
<div id="aic_1170">
<label for="1170">
<input type="checkbox" class="calccheckbox" value="1170" name="items[]" id="1170" />Item</label>
</div>
<div class="qtylbl" style="display:none;" id="qtylbl_1170">Quantity: <span class="qty" id="qty_1170"></span>
<a href="#" class="calcaddbutton" id="add1170">
<div class="calcbuttoncontainer"><span class="calcbutton glyphicon glyphicon-plus">+</span>
</div>
</a> <span class="calcbutton glyphicon glyphicon-minus">-</span>
</div>
</div>

You cannot animate the background-color with jQuery's default animate function.
What you can do, however, is position another div with a different color underneath your original div, and then animate the opacity on the original div, so that the color of the underlying div shows through, instead.

You can animate background color using Jquery UI library.
Include your jquery library and the jquery ui library, and it should work.
http://jqueryui.com/animate/

As multiple people mentioned, this isn't possible to do with jQuery, but it is possible with Velocity.js. And Velocity.js animations perform much better, especially on mobile!

Related

Jquery to toggle one div of same class on click

function demo(){
$('.box').slideToggle('fast');
}
$(document).ready(function(){
$.getJSON( "js/JobOpenings.json", function( data ) {
var glrScrlImg = [];
$.each( data.getJobOpeningsResult, function( key, val ) {
var st = "",id,st2= "",st3="",id;
st +="<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li onclick='demo()'>" + st+val.JobSector + "<br>" + st3 + "</li>");
$('.box').hide();
});
});
});
I am reading data from a json file. The div with 'box' class is hidden. Currently this code is displaying all div on click of the li. What changes should I make to display only the div corresponding to the clicked li?
Here what we need to do is to find the .box element within the clicked li, so we need to get a reference to the clicked element.
I would use a delegated jQuery event handler with css to initially hide the element
$(document).ready(function () {
$('#newsDetails').on('click', 'li', function () {
$(this).find('.box').toggleClass('hidden');
})
$.getJSON("js/JobOpenings.json", function (data) {
var glrScrlImg = [];
$.each(data.getJobOpeningsResult, function (key, val) {
var st = "",
id, st2 = "",
st3 = "",
id;
st += "<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box hidden'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li>" + st + val.JobSector + "<br>" + st3 + "</li>");
});
});
});
with css
.hidden {
display: none;
}
Pass the control to the function and then based on your control slideToggle its respective .box
function demo(ctrl){
$(ctrl).find('.box').slideToggle('fast');
}
$(document).ready(function(){
$.getJSON( "js/JobOpenings.json", function( data ) {
var glrScrlImg = [];
$.each( data.getJobOpeningsResult, function( key, val ) {
var st = "",id,st2= "",st3="",id;
st +="<h4>" + val.JobTitle + "</h4>";
st3 += "<div class='box'>" + val.JobDetails + "</div>";
$("#newsDetails").append("<li onclick='demo(this)'>" + st+val.JobSector + "<br>" + st3 + "</li>");
$('.box').hide();
});
});
});
Or add a class to li and attach an event handler like below instead of writing inline onclick as below:
$("#newsDetails").append("<li class="someclass"'>" + st+val.JobSector + "<br>" + st3 + "</li>");
and then instead of function demo() write this
$('#newsDetails').on('click','.someclass',function(){
$(this).find('.box').slideToggle('fast');
});
UPDATE
Method 1:
function demo(ctrl){
$('#newsDetails').find('li.box').hide('fast'); //hide all the .box
$(ctrl).find('.box').slideToggle('fast');
}
Method 2:
$('#newsDetails').on('click','.someclass',function(){
$('#newsDetails').find('li.box').hide('fast'); //hide all the .box
$(this).find('.box').slideToggle('fast');
});
UPDATE 2:
Method 1:
function demo(ctrl){
$('#newsDetails').find('li.box').not($(ctrl).find('.box')).hide('fast'); //hide all the .box
$(ctrl).find('.box').slideToggle('fast');
}
Method 2:
$('#newsDetails').on('click','.someclass',function(){
$('#newsDetails').find('li.box').not($(ctrl).find('.box')).hide('fast'); //hide all the .box except this
$(this).find('.box').slideToggle('fast');
});
You should structure your html (which is missing from the question!) so that the div and li are "connected" in some way (maybe the div is child of li, or they have same class, ecc).
Right now the line
$('.box').slideToggle('fast');
is applied to all element with class '.box' in your page. You want to be more selective there, that's where the way you structure the html comes into play.
Here's an example: http://jsfiddle.net/owe0faLs/1/

Textarea not generating from jQuery

I'm trying to make a website using jquery-1.11.1 where I want a <textarea> to be spawned whenever I click on the link which only shows on mouseenter on a div. But I'm getting an error in my console,
Uncaught ReferenceError: inputdivEditor is not defined (Please ignore JSFiddle errors)
I've absolutely no idea why I'm getting this. Here are my codes,
$(document).ready(function () {
$("[id^=divEditor-]").each(function () {
var content = $(this).html();
var targetID = $(this).attr('id');
var txtID = 'input' + targetID;
$('<textarea id="input' + targetID + '" name="' + txtID + '" >' + content + '</textarea>').insertBefore(this).css('display', 'none');
var button = "<a onclick='activateDivEditor(this, " + txtID + ")' class='custom-edit-button editDiv' id='active" + targetID + "'>Embed Code</a>";
$(this).on('mouseenter', function () {
$(this).prepend($(button));
$(this).css('position', 'relative');
});
$(this).on('mouseleave', function () {
$('.editDiv').remove();
});
});
});
function activateDivEditor(btn, txtId) {
var targetID = $(btn).parent().get(0).id;
var update = "<a onclick='deactivateDivEditor(this, " + txtId + ")' class='custom-edit-button updatediv' id='deactive" + targetID + "'>Update</a>";
var cancel = "<a onclick='cancelactivateDivEditor(this)' class='custom-edit-button cancel' id='cancelactive" + targetID + "'>Cancel</a>";
var targetClass = $('#' + targetID).attr('class');
var targetWidth = $('#' + targetID).width();
$('#' + targetID).css('display', 'none');
$('#input' + targetID).css('display', 'block').css('width', targetWidth - 2).css('height', '125px');
$('#input' + targetID).parent().css('position', 'relative');
$(update).prependTo($('#input' + targetID).parent());
$(cancel).prependTo($('#input' + targetID).parent());
}
JSFiddle Demo
How can I generate a textarea whenever I click on the button link? Need this help badly. Thanks.

jQuery - why do 2 elements get appended when I click an icon

I've created a JSfiddle here:
basically I have a form that will allow users to input additional sections... but when I have added more than 2 units and then proceed to click on the 'plus' (+) icon I get more than 1 element created in that section... its probably something elementary, but any info will help.
Move your Click functions out of the click function
//add unit input box and increment click counter by one.
addUnit.click(function () {
unitCounter += 1;
unitElementCount = jQuery(".unit-element").length;
if (unitCounter <= 4) {
error.hide();
container.append('<table id="unit-' + unitCounter + '-div" class="create-course-table-element unit-element"><tr><td><label class="unit-label">Unit ' + unitCounter + '</label></td><td><input class="create-course-input-element unit-input" id="unit-id-' + unitCounter + '" name="unit-' + unitCounter + '" /><div id="delete-unit-' + unitCounter + '" class="ui-icon ui-icon-circle-close del-unit" title="Delete unit"></div></td></tr><tr><td align="center">Sections</td><td><div id="add-section-icon-' + unitCounter + '" class="ui-icon ui-icon-plus add-section-icon"></div></td></tr></table><div id="section-id-' + unitCounter + '-div" class="this-section"></div>');
} else if (unitElementCount == 4) {
unitCounter = 5;
error.html("");
error.fadeIn(1500);
error.append("<p class='error-message'>Note: You are only able to add 4 units to a given course. Each unit allows you to add 10 separate sections of content; therefore you may add a total of 40 different sections to a given course. If the material requires more units, you should consider dividing the course into 2 parts.</p>");
}
});
//This part has been slightly modified and moved out of the addUnit.click() function
var counterSecTwo = 0;
var counterSecThree = 0;
var counterSecFour = 0;
jQuery(document).on("click", "#add-section-icon-2",function () {
counterSecTwo += 1;
var container = jQuery("#section-id-2-div");
container.append("<p>test "+counterSecTwo+"</p>");
});
jQuery(document).on("click", "#add-section-icon-3",function () {
counterSecThree += 1;
var container = jQuery("#section-id-3-div");
container.append("<p>test "+counterSecThree+"</p>");
});
jQuery(document).on("click", "#add-section-icon-4",function () {
counterSecFour += 1;
var container = jQuery("#section-id-4-div");
container.append("<p>test "+counterSecFour+"</p>");
});
});
Here I am binding the click handlers to Document as the elements do not exist yet: you could also add the event listener when you create the actual element.
Modified fiddle: http://jsfiddle.net/vewP7/

How to set focus on textbox on linkbutton click using javascript

I have this java script function
function showHideSearchPanel(dv) {
var Header = dv == 'Charts' ? 'ChartSearch' : 'ReportSearch';
var div = "ctl00_ContentPlaceHolder1_dv" + Header;
var panel = "ctl00_ContentPlaceHolder1_pnl" + Header;
var hiddenField = "ctl00_ContentPlaceHolder1_hdn" + Header + "Mode";
// I try to add this code in js but it not work
**var serchtextbox = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchName");
if (serchtextbox != null) {
serchtextbox.focus();
}**
// I try to add this code in js but it not work
if ($("#" + div).attr('display') != 'block') {
window.status = 'Expanding contents....';
$("#" + div).slideToggle("slow");
$("#" + div).attr('visibility', 'visible');
$("#" + div).attr('display', 'block');
window.status = 'Done';
}
else {
window.status = 'Collapsing contents....';
$("#" + div).hide("slow");
$("#" + div).attr('visibility', 'hidden');
$("#" + div).attr('display', 'none');
window.status = 'Done';
}
$("#" + hiddenField).attr('value', ($("#" + hiddenField).attr('value') == 'On' ? 'Off' : 'On'));
}
This is my simple menu
When click on search button i want set focu on search textbox which is in below image

Hover on one element causes hovering effect on other element with jQuery

I have to create the effect of bordered when I hover over element and vice versa.
I managed to do it, but the problem is that every time I hover over one of those elements I cancel the hovering effect on the element I was hovering over.
When I hover over with id="12345img" gets border and with id="12345a" gets color effect. When I do it vice versa it also works, but only for the first time I'm hovering over it.
This is the code.
<script type="text/javascript">
$(document).ready(function () {
$('.portfolioProject a').hover(function () {
var idElement = this.id;
$("#" + idElement.replace('a', '') + "img").css('border', '2px solid #cdfc5d');
$("#" + idElement + "a").css('color', '#cdfc5d');
});
$('.portfolioProject a').mouseleave(function () {
var idElement = this.id
$("#" + idElement.replace('a', '') + "img").css('border', 'none');
$("#" + idElement + "a").css('color', 'white');
});
$('.portfolioImage img').hover(function () {
var idElement = this.id;
$("#" + idElement.replace('img', '') + "a").css('color', '#cdfc5d');
$("#" + idElement + "img").css('border', '2px solid #cdfc5d');
});
$('.portfolioImage img').mouseleave(function () {
var idElement = this.id
$("#" + idElement.replace('img', '') + "a").css('color', 'white');
$("#" + idElement + "img").css('border', 'none');
});
});
</script>
My question is how to fix it to make it work every time.
jsFiddle link
I think you have to create CSS class for the mouse hover effect, Then you just Have to Toggle the class on event:
Jquery:
$(document).ready(function () {
$(".portfolioImageWrapper").on('mouseenter mouseleave', ".img", function () {
$(this).toggleClass('imgHover');
$("#" + (this.id).replace('img', '') + "a").toggleClass('imgHover');
});
});
HTML:
<div class='portfolioProject'>
<ul>
<h2>
<li>
<a id='7a' href='#'> Link1</a>
</li>
</h2>
<h2>
<li>
<a id='8a' href='#'> Link 2 </a>
</li>
</h2>
</ul>
</div>
<div class='portfolioImageWrapper'>
<div class='portfolioImage'><a href='#'><img class="img" src='#' alt='Image1' title='Image 1' id='7img' /></a></div><div class='portfolioImage'><a href='#'><img class="img" src='#' alt='Image 2' title='Image2' id='8img' /></a></div></div>
​CSS:
.imgHover
{
border-style: dotted;
border-width: 1px;
color: red;
text-decoration: none;
}​
jsfiddle
You can toggle a different css class to your links for sure. Just modify this in jquery code (in the toggleClass function) and add the class to the css part
Do you want that when you hover over a link, the image should get bordered and when you mouse out from the link, the border of the image should get removed ?
Also, when you hover over an image, the link should get colored and when you mouse out the image, the link should go back to its original color ?
If that is the requirement, this code might help:
$(document).ready(function () {
$('.portfolioProject a').hover(
function ()
{
var idElement = this.id;
$("#" + idElement.replace('a', '') + "img").css('border', '2px solid #cdfc5d');
$("#" + idElement + "a").css('color', '#cdfc5d');
},
function()
{
var idElement = this.id;
$("#" + idElement.replace('a', '') + "img").css('border', 'none');
$("#" + idElement + "a").css('color', 'white');
}
);
$('.portfolioImage img').hover(
function ()
{
var idElement = this.id;
$("#" + idElement.replace('img', '') + "a").css('color', '#cdfc5d');
$("#" + idElement + "img").css('border', '2px solid #cdfc5d');
},
function()
{
var idElement = this.id
$("#" + idElement.replace('img', '') + "a").css('color', 'blue');
$("#" + idElement + "img").css('border', 'none');
}
);
});
Check out the fiddle: http://jsfiddle.net/B47Gu/
I have modified the fiddle, will this serve your purpose: http://jsfiddle.net/B47Gu/3/

Categories