Second click funcktion on a div? - javascript

On the first click the div should become red and I want it to become white on the second click but I do not know how. I need code that makes the div white on the second click.
function red() {
document.getElementById("red").style.backgroundColor = "red";
}

You can do this:
Var colors[]=["red","white",...]; //colors that are to be selected in order.
Var clicked=0; // no. Of clicks
//call this function when the div is clicked like this <div onclick="changeColor()" .....
function changeColor(){
document.getElementById(divId).style.background =colors[clicked]; //change color according to clicks
clicked++; // increase no. Of clicks by 1
/*if you want to repeat the pattern */
if(colors.length==clicked){
clicked=0;
}
}

Add a class to the element and use jquery toggleClass for more detail read this.

Related

jquery show hide not working properly

I've made an animation which fades in and out.
I have two buttons $('.point li') to show two different contents $("#"+classVal+" .table-cell")
However, when I click $('.point li'), I'd like to gradually show its content from white background.
But its opacity remained when I click another button and click back.
Is there a way to show the content from zero opacity every time I click the button?
var q = $('#intro .table-cell'); //this is a first content to show
var qIndex;
$(window).ready(function(){
$('.point li').click(function(){ //click a button
$('.point li').removeClass('active');
var classVal = $(this).attr('class');
$(this).addClass('active');
q.stop(true,false);
$('.bg > div').css('display','none');
$('.bg > div .table-cell').css('display','none');
$('#'+classVal).css('display','block');
q = $("#"+classVal+" .table-cell");
qIndex = -1;
showNextQ();
});
});
function showNextQ() {
++qIndex;
q.eq(qIndex % q.length).show(2000).delay(1000).hide(2000, function(){
showNextQ();
});
}
I found a solution.
The reason why the animation's attributes remained is that JQuery store it to a variable.
So I change the second parameter in a function "stop"
q.stop(true,false);
to True
q.stop(true,true);
which means "jump to end"
Than it works

After click return to initial state

Hello I got a question regarding changing elements in the DOM. I got a situation that whenever I click on the button it will show a div. After 2 seconds the initial div is replaced by another div which also got a function call that removes the div again.
Now comes the tricky part. What I want is that whenever I hide the div again, the third click on the button will show the div again.
Let me explain a bit more. Imagine that I got the following situation:
First mouse click on button 1 (Result: shows red div)
Second mouse click on button 1 (Result: hide red div)
Third mouse click on button 1 (shows the div again)
The third bullet is the tricky one. How can I do that? Because when I click for the third time on button 1 it does not show anything anymore because I did not change it back to the original state
The code that I have so far JSFIDDLE
function Test(){
var target = window.event.target || window.event.srcElement;
console.log(target);
var content = arguments[0];
console.log(content);
$( "body" ).append( "<div class='red'>"+content+"</div>" );
setTimeout(function(){
$( ".press" ).replaceWith( "<button class='press' onclick='UnTest()'>button 1</button>" );
}, 2000);
}
function UnTest(){
$( ".red").remove();
}
Please note that due to implementation restrictions I can not check within my Function if the button is clicked (eq. $(".red").click())
There are a few ways you could accomplish this, but a quick solution might be just toggling the onclick attribute of the button (rather than replacing it entirely).
// In setTimeout
setTimeout(function(){
$('.press').attr('onclick', 'UnTest()');
}, 2000);
function UnTest(){
$( ".red").remove();
$('.press').attr('onclick', 'Test("one")');
}
https://jsfiddle.net/2mvqmtwq/1/
This will also allow you to add multiple .red divs (similar to the original fiddle) and then remove with a single click (which another answer does not take into account, instead treating it as a simple visibility toggle).
Edit: For multiple buttons/instances (per your comment), you'll need an identifier of sort. Your original code made it easy by declaring the target, which we can use. Let's say we have three buttons:
<button class="press" onclick="Test('one')">button 1</button>
<button class="press" onclick="Test('two')">button 2</button>
<button class="press" onclick="Test('three')">button 3</button>
Our updated JS doesn't change too much, other than referencing the string value we passed (which you declare as content):
setTimeout(function(){
$(target).attr('onclick', 'UnTest("' + content + '")');
}, 2000);
As well as referencing the target you've declared at the top (which allows us to keep each button instance unique).
Here's the updated fiddle with all the changes I made (additional parameters, scoped class names for the red boxes, etc):
https://jsfiddle.net/2mvqmtwq/9/
Use a variable to count the number of clicks, which is initially equal to 0. Then, each time you click the button, you increase the variable by 1 and check if the variable is odd or even. If it's odd, you add the div, if it's even you remove the div:
var clicked = 0;
function Test() {
clicked++;
var content = arguments[0];
if (clicked % 2 === 1) {
$("body").append("<div class='red'>" + content + "</div>");
} else {
$(".red").remove();
clicked = 0;
}
}
Fiddle: https://jsfiddle.net/2mvqmtwq/5/
Tip: you can reset the variable back to 0 when it's even.
Here's a dead simple fix. I think we can do this whole thing a lot more cleanly with some refactoring. But since you mention implementation restraints, I don't want to offer a solution that might break those restraints.
Simply add logic to your UnTest() function
function UnTest(){
$( ".red").remove();
$( ".press" ).replaceWith( "<button class='press' onclick='Test(\"hello\")'>button 1</button>" );
}
How about writing some clean code, avoiding inline event handlers?
What you could probably do is:
First click: add the div
Next click onwards: check if the div already exists. If yes, simply toggle it's display as opposed to removing it.
This is only a demo as to how this could be done. This one also works for multiple buttons/divs. As I said earlier, I have removed inline event handlers and added the div class and function params as data-attributes. Feel free to edit the code to suit your needs.
$(document).on("click", ".press", function() {
var $this = $(this);
var $div = $("div." + $this.data("class"));
if ($div.length) {
$div.toggle();
return;
}
$( "body" ).append( $("<div/>", {
'class': $this.data("class"),
'html': $this.data("param")
}) );
});
button{ margin:10px}
div {
width:200px;
height:50px;
}
.red {
background-color:red;
}
.blue {
background-color:blue;
}
.green {
background-color:green;
}
.orange {
background-color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="press" data-param="one" data-class="red">button 1</button>
<button class="press" data-param="two" data-class="blue">button 2</button>
<button class="press" data-param="three" data-class="green">button 3</button>
<button class="press" data-param="four" data-class="orange">button 4</button>

Change word color and counter with each click Jquery

I have white text in 10 divs that should become blue once the user clicks on them and the total number of "selected" divs is 5. I did it like this:
<div id="sen1" class="sentences">Text1</div>
<div id="sen2" class="sentences">Text2</div>
<div id="sen3" class="sentences">Text1</div>
<div id="sen4" class="sentences">Text2</div>
...
$(".sentences").click(function() {
count++
$(this).css("color", "blue")
selected_true.push($(this).text())
if (count == 5){
$(".sentences").off("click")
//go to next page
}
});
Now I want the text to become white again if a blue text is clicked again and want to decrease the count variable by one. So ideally I want to increase the counter each time a sentence is selected and decrease it again once it is un-selected.
I thought about toggle but how would I incorporate the counter in the toggle method?
Doing it this way might make more sense:
css
.sentences {
color: #fff;
}
.sentences.turnedon {
color: blue;
}
javascript
$(".sentences").click(function() {
if( $(this).hasClass('turnedon') ) {
$(this).removeClass('turnedon');
count-1;
} else {
$(this).addClass('turnedon');
count++;
}
You can do it using 2 classes. If you have 2 styles classes you can use.
$('yourSeletor').toggleClass('yourClassBlue');
See this example: http://api.jquery.com/toggleclass
A better approach would be to add a class to each clicked div and remove it when it is clicked again.
Use the JQuery toggleClass to get it done in one simple line:
$(this).toggleClass('selected');
Then you can count the selected divs like so:
$('.selected').length;

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.

javascript set element background color

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

Categories

Resources