javascript set element background color - javascript

i have a little javascript function that does something when one clicks on the element having onclick that function.
my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:
<script type="text/javascript">
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6) stock=6;
for (i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
}
</script>
and how i use it:
<li id = "product_types">
<a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
any suggestions? thanks!
i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:
$(document).ready(function() {
$('.product_types > li').click(function() {
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','#ffffff');
});
});
any ideas why?
thanks!

I would suggest
$(document).ready(function() {
$('.product_types > li').click(function() {
$('.product_types > li').css('background-color','#FFFFFF');
$(this).css('background-color','#EE178C');
});
});

Your element could have this code:
<li id = "product_types" onclick="selecteazaElement(this);" <...> </li>
To change the foreground color of that element:
function selecteazaElement(element)
{
element.style.foregroundColor="#SOMECOLOR";
}
If you want to change the background color on only the last element clicked, each element must have a different id. I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on. Then have a reset function:
function Reset()
{
for (var i = 1; i <= N; i = i + 1)
{
document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
}
}
When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:
function selecteazaElement(element)
{
Reset();
element.style.backgroundColor="#SOMECOLOR";
}
This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.

The 'scope' of the function when invoked is the element clicked, so you should be able to just do:
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23 = document.addtobasket.number;
number23.options.length=0;
if (stock>=6){
stock=6;
}
for (var i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
// Alter 'this', which is the clicked element in this case
this.style.backgroundColor = '#000';
}

$(function() {
/*if product_types is a class of element ul the code below
will work otherwise use $('li.product_types') if it's a
class of li elements */
$('.product_types li').click(function() {
//remove this class that causes background change from any other sibling
$('.altBackground').removeClass('altBackground');
//add this class to the clicked element to change background, color etc...
$(this).addClass('altBackground');
});
});
Have your css something like this:
<style type='text/css'>
.altBackground {
background-color:#EE178C;
/* color: your color ;
foo: bar */
}
</style>

Attach a jQuery click event to '#product_types a' that removes a class from the parent of all elements that match that selector; then, add the class that contains the styles you want back to the parent of the element that was just clicked. It's a little heavy handed and can be made more efficient but it works.
I've made an example in jsFiddle: http://jsfiddle.net/jszpila/f6FDF/

try this instead:
//ON PAGE LOAD
$(document).ready(function() {
//SELECT ALL OF THE LIST ITEMS
$('.product_types > li').each(function () {
//FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
$(this).click(function() {
//GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','transparent');
});
});
});
If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.
I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.
Cheers,
-Robert Hurst

Related

Zooming class added to all images in slider without checking if the 'li' is active

I have a problem with flexslider 2 and elevate zoom plus.
I would like to zoom active image from the slider. I have to use this option, because I also use ACF in wordpress and only this one works as I want. Unfortunately code which I created doesn't work as it should
$(document).ready(function() {
if ($('.flexslider .slides > li').hasClass('flex-active-slide')) {
$('.flexslider .slides li img').addClass('zooming');
}
else
{
$('.flexslider .slides li img').removeClass('zooming');
}
});
</script>
When the li has class which means that image is active, then I would like to add class to the image which has to be zoomed. Unfortunately it adds zooming class to all images in slider without checking if the li is active. What am I doing wrong?
No need to add different js for this, you can add in initialization only like below:
$(window).load(function () {
$('.flexslider').flexslider({
animation: "slide",
start: function (slider) {
$('body').removeClass('loading');
$(slider).find(".flex-active-slide img").addClass("zooming"); // this will add class on slider start
},
before: function (slider) {
$(slider).find(".zooming").each(function () {
$(this).removeClass("zooming"); // this will remove class from previous tag
});
},
after: function (slider) {
$(slider).find(".flex-active-slide img").addClass("zooming"); // this will add class in next tag
}
});
});
Your logic is close, but you are targeting all images with this line:
$('.flexslider .slides li img').addClass('zooming');
It also has to run every time the classes of the slide > li changes.
Unfortunately jQuery doesn't have something nice like .classChange(), but here is a function - created by kozachenko on github - which does what we want.
So you can add kozachenko's function and then use it to see if the class of the li has changed, then add/remove your zooming class.
To find only the one you're looking for, you can use the active class as a selector, and then use jQuery.find() to look for the image inside of that particular element.
$(document).ready(function(){
//kozachenko's function https://gist.github.com/kozachenko/30e55fb5f9ae170eedfe258430fd09ec
(function(){//adds a trigger step to the addClass/removeClass jQuery functions
var originalAddClassMethod = jQuery.fn.addClass;
var originalRemoveClassMethod = jQuery.fn.removeClass;
jQuery.fn.addClass = function(){
var result = originalAddClassMethod.apply( this, arguments );
jQuery(this).trigger('classChanged');
return result;
}
jQuery.fn.removeClass = function(){
var result = originalRemoveClassMethod.apply( this, arguments );
jQuery(this).trigger('classChanged');
return result;
}
})();
$('.flexslider .slides > li').on('classChanged', function(){//the new event triggered by addClass()/removeClass()
$(this).find('img').removeClass('zooming');//first remove the class from any other image
$('.flex-active-slide').find('img').addClass('zooming'); //add the class to active image
});
});

Edit div class name on click

So basically I have a bunch of nav buttons that I want to change the name of when the user clicks the button.
The original div class name is something like "home", and when the user clicks on it I want it to be "home_active" so that the CSS attributes will change the background-image.
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).attr('class') = updated_url;
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3
You shall use the .addClass() method add a class to the element:
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(clicked_url); // remove the old class
$(this).addClass(updated_url); // add the new class
});
However, as a good practice, it is better to add a modifier class, such as "active" to the existing class, preserving the original class name.
Then use the following CSS:
.click.active {
background: red;
}
The JS code would look like this:
$('.click').click(function() {
$('.click.active').removeClass('active'); // remove active class from all other nav items
$(this).addClass('active'); // add active to the nav item the users just clicked on
});
Using Jquery functions:
$(this).hasClass("className");
$(this).addClass("className");
$(this).removeClass("className");
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(updated_url)
$(this).addClass(updated_url)});
Almost there - but remember to use attr to reset the class value. And you most likely want to remove _active from the other .click elements, so this is the only one.
$(".click").click(function() {
$(".click").each(function() {
$(this).attr("class", $(this).attr("class").replace(/_active/, ""));
});
$(this).attr("class", $(this).attr("class") + "_active");
});
Not sure where class .click is but there is .item and .click(...) method is ok -- I prefer to use .on('click', ...) (see the difference between .click() and .on()).
$('.item').on('click', function() {...
Since objective is to simply change the style of a clicked link by changing its class then it's better to assign a common class (which was done: .item) and a class that sets the state (a separate class: .active).
$(this).toggleClass('active');
If you wish to apply this to additional tags, simply modify the outer selector
$('.item, :button').on('click', function() {...
The selector above will listen for clicks on anything with the class .item and any <button> and <input type='button'> tags.
It wasn't very clear what the desired behavior was so there's two demos:
Demo 1: Click any link to add/remove .active class
or
Demo 2: Click any link to add/remove .active class exclusively
Demo 1
Click any link to add/remove .active class
$('.item').on('click', function() {
$(this).toggleClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo 2
Click any link to add/remove .active class exclusively
$('.item').on('click', function() {
$(this).toggleClass('active');
$('.item').not(this).removeClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Couple things. First, you want to select elements with a class name of "item," not "click." Secondly, you were using the attr() function wrong. Instead of attr('class') = var, you want to set the var as the second parameter, e.g. attr('class', var).
Edit: Finally, you should check in your click event whether or not the link has been previously clicked (i.e. whether it already has the "_active" suffix):
$('.item').click(function() {
var clicked_url = $(this).attr('class');
var updated_url;
if(clicked_url.includes("_active")){
updated_url = "item";
}else{
updated_url = "item_active";
}
$(this).attr('class', updated_url);
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

remove onclick when attached to children

I have the following code:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div", function(event) {
var floor;
console.log("floornum: " + this.dataset.floornum);
floor = parseInt(this.dataset.floornum);
...
$("#choose-floor").fadeOut();
$("#choose-apt").fadeIn();
});
later - based on data I'm getting back from the DB - I want to remove some of the .on("click", "div", ...) from only some of the divs. I already have the selector that is getting the right divs but I cannot figure out how to remove the click event. I have tried .off("click") after selecting the right div but it has no effect.
This issue here is because you are using a delegated event. You can add or remove the event for all child elements, but not individual ones given your div selector.
With that in mind the easiest way to do what you need is to add the event based on a class, then add and remove that class on the children as needed. Something like this:
layoutOverlaysBldg = $("#layout-overlays-bldg")
layoutOverlaysBldg.on("click", "div.clickable", function(event) {
// your code...
});
You can then enable/disable the event on the child div by adding or removing the .clickable class.
You can try like this :
Example :
<div id="test">
<div id="first">first</div>
<div id="second">second</div>
</div>
<div onclick="unbindSecondDiv();">UNBIND</div>
<script>
function unbindSecondDiv()
{
test = $("#second")
test.unbind("click");
alert('Selected Area Click is Unbind');
}
$(document).ready(function(){
//BIND SELECTED DIV CLICK EVENT
test = $("#test > div")
test.bind("click" , function(event) {
alert($(this).attr('id'));
});
});
</script>
In the above example , selected DIV elements click event is bind.
And after execute function unbindSecondDiv() , second DIV click event will be unbind.
Have a try , may helps you.

Change selected tr color back after selecting new tr

Thus far I've figured out most of the code I need to select a radio button inside of a <tr> when the row is clicked & to change the color of the <tr> when it's clicked, but I need to be able to change the color back & change the color of a new <tr> if the user selects a different one. Right now it just keeps changing the color of the rows, but doesn't change them back. Code is below:
<script>
var prevTr;
$('tr').click(
function() {
$('input[type=radio]',this).attr('checked','checked');
$(this).addClass('selectedtr');//css('background-color', 'Green');
prevTr = $(this).id;
$("#"+prevTr).removeClass('selectedtr');
}
);
...
Remove the selectedtr class from all tr elements first, then add it to the current one:
$('tr').click(
function() {
$('input[type=radio]',this).prop('checked','checked');
$(this).siblings().removeClass('selectedtr');
$(this).addClass('selectedtr');
}
);
Edit - I don't think David Thomas's answer is quite what you're looking for, but I do think the siblings() select would be more efficient than selecting all tr elements.
Another Edit
In reference to your comment: prop should be used instead of attr. Here's a fiddle:
http://jsfiddle.net/xQyAV/
I would use css:
binput[type=radio]:hover {
//here edits
//the setting back happens automaticly
}
I'd suggest:
$('input[type=radio]').change(function (){
var self = this,
row = $(self).closest('tr');
row.addClass('trSelected').siblings().removeClass('reselected');
});
I think it only needs to remove the class before remembering the current identifier:
$(function () {
var prevTr = false;
$('tr').click(function () {
if (prevTr) {
$("#" + prevTr).removeClass('selectedtr');
}
prevTr = $(this).id;
$('input[type=radio]', this).attr('checked', 'checked');
$(this).addClass('selectedtr');
});
});

Categories

Resources