jquery/javascript - how to "undo" a click event using if statement? - javascript

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.
<script>
$(document).ready(function() {
$("p, h1").click(function() {
$(this).css("background-color", "red");
if ($(this).css("background-color", "red")) {
$(this).css("background-color", "null");
}
});
});
</script>

First you need to use the getter version of .css() like
if($(this).css("background-color") == "red"){
but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.
So the solution is to use a css based solution using toggleClass()
.red {
background-color: red;
}
then
$(document).ready(function() {
$("p, h1").click(function() {
$(this).toggleClass("red");
});
});
Demo: Fiddle

$('p, h1').click(function() {
var $this = $(this);
var altColor = $this.data('altColor');
$this.css('background-color', altColor ? '' : 'red');
$this.data('altColor', ! altColor);
});
This answers your question, but you should really be using a CSS class for this.

This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:
CSS
p, h1 {
background-color: none;
}
p.red, p.h1 {
background-color: red;
}
JavaScript:
$('p, h1').click(function() {
$(this).toggleClass('red');
});

Related

how to change css in jquery with set Attribute method?

i have a simple of jquery ios button, and i want when user clicks on it and it is on, background color of page should be black and when button is off background color should be red for instance....
this is jsfiddle: https://jsfiddle.net/urbb4rgx/
what i appended to jquery:
var one = getElementsByClassName("switch"),
var two = getElementsByClassName("switchOn"),
if (two.hasOwnProperty("switchOn")) {
document.getElementsByClassName("switchOn").background: red;
}
else {
document.getElementsByClassName("switchOn").background: black;
}
please explain me what i did wrong
thanks...
With jQuery try the following . --Update
Everything in your code looks fine . Just modify it to the following
$(document).ready(function(){
$('.switch').click(function(){
$(this).toggleClass("switchOn");
$("body").toggleClass("black");
});
$('.switchBig').click(function(){
$(this).toggleClass("switchBigOn");
});
});
You will need to create a class to set Default background color :
body {
background-color:red;
}
.black{
background-color:black;
}
Working example here: http://codepen.io/theConstructor/pen/bpgPvB

Disable/Enable CSS on webpage using Javascript

According to This page I was able to remove all the CSS preloaded and added on the webpage using that. I wanted to implement a button system where "onclick" = enable/disable webpage CSS even the ones pre-loaded by my web-host. I would like to eliminate the style tags to prevent lags for my website users. I prefer using the script that I have linked above unless there is another alternative that works better. Is it possible to enable CSS onclick the same button to disable? If not is it possible, can it be done with this quick? example with the preferred script below:
if (disable) {
style = "disable";
} else {
location.reload();
}
PREFERRED SCRIPT:
function removeStyles(el) {
el.removeAttribute('style');
if(el.childNodes.length > 0) {
for(var child in el.childNodes) {
/* filter element nodes only */
if(el.childNodes[child].nodeType == 1)
removeStyles(el.childNodes[child]);
}
}
}
removeStyles(document.body);
What about a different aproach?
Add initially a class to a body called 'styled' for example
<body class="styled">
use it as a main selector in your css definitions
<style>
.styled a { ... }
.styled h1 { .... }
</style>
then an example jquery script to toggle the class:
<script>
$(function() {
$('#myswitch').click(function() {
$('body').toggleClass('styled');
});
});
</script>
when class is present, the page will be styled, when absent there will be no styling.
Of coures there could be better aproach, but this is the first thing which pops up in my mind
To remove all style on an element, you could do
function removeStyles(el) {
el.style = {};
}
If you want to enable/disable the CSS on the page, then the goal is not to merely remove all the styles on the page, but you will need to save them somewhere also so they can be recalled when the user re-clicks the button. I would recommend having jQuery to help you with this, and it could be done the following way:
var style_nodes = $('link[rel="stylesheet"], style');
style_nodes.remove();
$('*').each(function(num, obj) {
var style_string = $(obj).attr("style");
if (style_string) {
$(obj).data("style-string", style_string);
$(obj).attr("style", "");
}
});
Now you've saved the stylesheets and style DOM nodes inside of style_nodes, and the actual style attribute inside of a jQuery data attribute for that specific DOM node. When you click to add the CSS back to the page, you can do the following:
$('head').append(style_nodes);
$('*').each(function(num, obj) {
if ($(obj).data("style-string"))
$(obj).attr("style", $(obj).data("style-string"));
});
Check out this JS Fiddle I put together to demonstrate it:
https://jsfiddle.net/5krLn3w1/
Uses JQuery, but I'm sure most frameworks should give you similar functionality.
HTML:
<h1>Hello World</h1>
Turn off CSS
Turn on CSS
JS:
$(document).ready(function() {
$('a#turn_off').click(function(evt) {
evt.preventDefault();
var css = $('head').find('style[type="text/css"]').add('link[rel="stylesheet"]');
$('head').data('css', css);
css.remove();
});
$('a#turn_on').click(function(evt) {
evt.preventDefault();
var css = $('head').data('css');
console.info(css);
if (css) {
$('head').append(css);
}
});
});
CSS:
body {
color: #00F;
}
h1 {
font-size: 50px;
}

Add class on div mouse enter mouse leave and click

What i am trying to achieve is, i want to make it work like star rating. When you enter mouse star becomes yellow, when you leave mouse it turns gray and then if you click it again becomes yellow.
Not getting how to achieve it, I have added code to show you what i have tried so far.
JSfiddle
$(".na").hover(
function () {
$(this).addClass("clickstar");
},
function () {
$(this).removeClass("clickstar");
}
);
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
.clickstar{
background: #00A1EF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="na" style="border:1px solid #c0c0c0;border-radius:50%;width:115px;height:115px;display:inline-table;margin-right:5px;"></div>
You should consider using 2 different classes, .hoverstar and .clickstar, then :
http://jsfiddle.net/xLxbw216/1/
You would have one class for each case, which seems more logical ?
You can also make it simpler by removing .hover() method, and do it with CSS :
http://jsfiddle.net/xLxbw216/8/
I probably choose the second one, even if the first solution seems to be more "readable".
You can do it like this:
$(".na").on("click",function(){
$(this).toggleClass("clickstar");
});
Fiddle Example
You should use a different class for permanent start and hover star
I have created a working example in JSfiddle
$(".na").hover(
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$this.addClass("clickstar");
}
},
function () {
var $this = $(this);
if (!$this.hasClass("permstar")) {
$(this).removeClass("clickstar");
}
}
);
$(".na").on("click",function(){
$(this).toggleClass("permstar");
});
add/remove class on hover events was conflicting with on click event, so i have moved the hover functionality to css
css:
.clickstar{
background: #00A1EF;
}
.na:hover{
background: #00A1EF;
}
live demo:
http://jsfiddle.net/dreamweiver/xLxbw216/7/
Happy Coding :)

how to make javascript function call two divs

i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}

How to switch between 2 CSS colors with jQuery?

I want a string of text to change color from default to #c30 when I click a button somewhere on the page, and it changes back to default when I click the button again.
My code looks like this:
$("#button").click(function() {
var anno = $(#text);
if (anno.css('color') == '#c30') {
anno.css('color', '');
} else {
anno.css('color', '#c30');
}
});
But it doesn't seem to work on FF3. Works in IE though. Any idea?
I would try to separate the presentational details as much as possible, i.e. change the classes to which the element belongs, and leave the colour information in a separate stylesheet.
$("#button").click(function() {
$("#text").toggleClass('somethingDescriptive');
});
If you use named colors, this will work.
$("#button").click(function(){
$("#text").css('color', $("#text").css('color') == 'white' ? 'black' : 'white');
});
Hex values do not.
This is a bad way to do it anyways, I agree with the most voted up answer here. So I have updated my answer after some research.
<style type="text/css">
.color1 { color:#fff; }
.color2 { color:#000; }
</style>
<script>
$("#button").click(function(){
$("#text").toggleClass('color1').toggleClass('color2');
});
</script?
<div class="color1">Text</div>
The color #c30 is converted to #cc3300 - that's why it is not working.

Categories

Resources