Remove CSS hover functionality using Javascript - javascript

I need to remove CSS hover functionality using JavaScript.
I have a button on a form which submits data to our db server. Using OnClientClick() of an ASP.NET Button control I would like to change the element's text to 'Submitting..' using getElementById(), change the background color of the button to Light Grey and more importantly disable the following .button:hover effect I have in my CSS.
.button:hover,
.content-form input.button:hover,
#comment-form #submit:hover
{
background-color: #333;
}
All I am really interested in is the Javascript to remove/disable the above CSS
e.g. OnClientClick="getElementByID('ButtonName').blahblahblah;"

Working fiddle: https://jsfiddle.net/bm576q6j/17/
var elms = document.getElementsByClassName("test");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("gray");
};
}
Edit: Sorry for not noticing last part of your question before I answered :)

There are a lot of solutions for solving your problem.
For example:
1- Using HTML disabled attribute.
OnClientClick="getElementByID('ButtonName').disabled=true;
2- Add a class which overrides the previous style.
.button:hover,
.content-form input.button:hover,
#comment-form #submit:hover
{
background-color: #333;
}
.button.submitted:hover
{
background-color: gray;
}
Js:
OnClientClick="getElementByID('ButtonName').className = "submitted";
and etc

In this case it removes the class attribute eliminating all defined classes, but then adds that should not be removed.
On jsfiddle
function disableHover(elem) {
elem.removeAttribute('class');
elem.setAttribute('class', 'another');
}
.button:hover {
background-color: #333;
}
.another {
background-color: lightgray;
}
<button class="button" onclick="disableHover(this);">hover</button>
But the best way of doing this is so, simple and works well.
function disableHover(elem) {
elem.classList.remove('button');
elem.classList.add('another');
}
.button:hover {
background-color: #333;
}
.another {
background-color: lightgray;
}
<button class="button" onclick="disableHover(this);">hover</button>
On jsfiddle

First of all your css is wrong. It should be:
.button:hover, .content-form input.button:hover, #comment-form, #submit:hover {
background-color: #333;
}
and you are adding css with id and class. You should not do that. Just add with class and use document.getElementById('submit').removeAttribute('class')

Related

Best way to switch between two colours with javascript?

Javascript beginner here. I essentially want to make a simple switch. If an element is black, change it to white. If it is white, change it to black.
function changeClass() {
if (document.getElementById('myButton').style.backgroundColor == "white") {
document.getElementById('myButton').style.backgroundColor = "black";
} else {
document.getElementById('myButton').style.backgroundColor = "white";
}
}
<button class="normal" id="myButton" onclick='changeClass()' >Change Colour</button>
This code is quite messy though. Is there a better way to do this?
Toggle a class:
function changeClass(){
document.getElementById('myButton').classList.toggle("the-class");
}
where your CSS is:
.the-class {
background-color: black;
}
...assuming the element's normal background color is white.
More about classList here. Support is good, but you may need a polyfill in older environments.
Example:
function changeClass() {
document.getElementById('myButton').classList.toggle("the-class");
}
.the-class {
background-color: black;
}
<button class="normal" id="myButton" onclick='changeClass()'>Change Colour</button>
You can use classList.toggle()
document.querySelector('#myButton').addEventListener('click',e => {
e.target.classList.toggle('black')
})
.black{
background:black
}
<button class="normal" id="myButton">Change Colour</button>
Use something like classList.toggle()
function switchColor(){
document.getElementById("resultDiv").classList.toggle("toggle")
}
.element {
height: 100px;
width: 100px;
background-color: red;
}
.element.toggle{
background-color: blue !important;
}
<button onclick="switchColor()">Click me</button>
<div id="resultDiv" class="element toggle"></div>
You can create some specific class in your css (say, .black class which contains a background-color: black; rule) and then attach/detach that class based on your condition.
Your DOM element (HTML tag) have a handy classList property, which can be treated as a list of classes attached to this DOM. I suggest to read a bit more about it here.
Overall, your function can be written like:
const element = document.getElementById("coolDiv");
element.classList.contains('black')) {
element.classList.remove('black')
} else {
element.classList.add('black')
}
or even a little more concise with a ternary operator
const element = document.getElementById("coolDiv");
element.classList.contains('black') ?
element.classList.remove('black') : element.classList.add('black')
or just with a toggle function of the same classList property
const element = document.getElementById("coolDiv");
element.classList.toggle('black')
Hope it helps! Cheers!
and if white it's not the defualt color you can refactor using ? operator:
let btn = document.getElementById('myButton');
btn.style.backgroundColor = btn.style.backgroundColor === 'white' ? 'black' : 'white';
For this action not needed external javascript you can write simple inline javascript here the code:
.black-button {
background: black;
color: #fff;
outline: 0;
padding: 20px;
}
button {
transition: 0.3s;
cursor: pointer;
}
<button class="normal" onclick="this.classList.toggle('black-button')">Change Colour</button>

JavaScript Accordion - Disable closing the panel

I have an accordion based on JavaScript and CSS. When the user clicks on a panel, it opens and the header gets a different color. When the user clicks on another panel, the panel selected before is closed and the new one opened.
What I don't want is the user to be able and close the active panel. This is because the header color does not change back and I also change the color of features on the map. If it cannot be disabled, is there a way to access the closed panel so that I can change back the color of the header?
I tried to make a JS fiddle, but I cannot integrate my code, this does not work. The fiddle: https://jsfiddle.net/s0y639ra/6/
This is my code:
JavaScript:
var acc = document.getElementsByClassName('accordion');
var panel = document.getElementsByClassName('accordion-panel');
for (var i = 0; i < acc.length; i++)
{
(function(index){
acc[i].onclick = function()
{
var setClasses = !this.classList.contains("active");
setClass(acc, 'active', 'remove');
setClass(panel, 'show', 'remove');
if (setClasses){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
var myIndex = index + 1;
console.log("INDEX " + myIndex);
//set the style of the route
routes.setStyle(style_routes);
routes.getLayer(myIndex).setStyle(style_routeClicked).bringToFront();
//zoom to the selected feature
map.fitBounds(routes.getLayer(myIndex).getBounds(),{padding:[200,200]});
}
})(i);
}
function setClass(els, className, fnName){
for (var i=0; i < els.length; i++){
els[i].classList[fnName](className);
}
}
The CSS:
button.accordion {
margin-left: -10px;
background-color: white;
color: #444;
cursor: pointer;
padding: 18px;
height: 100%;
width: 110%;
text-align: left;
border: 0;
border-bottom: 1px solid;
outline: none;
transition: 0.4s;
}
button.accordion {
background-color: #f8f8f8;
}
button.accordion:hover {
background-color: #426334;
color: white;
}
button.accordion:focus {
background-color: #426334;
color: white;
font-weight: bold;
}
div.accordion-panel {
padding: 0 0px;
background-color: none;
display: none;
}
div.accordion-panel.show {
display: block !important;
}
There are two different solutions to that question. While it is quite hard to answer without an usable sample... could you include an jsfiddle link?
One solution would be your requested behavior (user can not close open panel). To achive this you can just check if the active class of the clicked element is already set and only if not you will execute all the other functions you implemented. (Move everything to your if(setClasses){})
The other solution would be to just search for each header having the "active" class before setting the new one this way you can find the index, if you really need it. A better way in my opinion would be to have an identifyer on each trigger which you can use to identify the corresponding elements (e.g. a data-index="XX")

Keep an image selected

I have a program which allows the user to select some images and i gave them the pseudo class
.my_image_clas:hover{
border:3px solid blue;
-webkit-box-sizing: border-box; }
to make them surrounded with borders when the pointer goes over (giving a "selected effect"). I'd like to keep this effect even when i select the image, like this :
How can i achieve this? (With javascript)
CSS-only "hack"
At first this question asked for CSS-only solution and while, as others have said, it's not really possible to achieve what you ask for without JavaScript, there is a CSS-only hack, however:
img {
margin: 3px;
width: 100px;
}
img:hover, img:target {
border: 3px solid green;
margin: 0;
}
<img id="a" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" />
<img id="b" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" />
It works by making your images a target of a click on an anchor they are contained in. We can style elements that are link targets, because we have a selector for that in CSS.
Note that this way you can select only one image.
Pure JavaScript
If you want to do it with JavaScript though, you can use below code:
function select(element) {
element.onclick = function() {
element.classList.toggle('selected');
}
}
Array.from(document.getElementsByClassName('selectable')).forEach(select);
img {
margin: 3px;
}
.selected {
border: 3px solid green;
margin: 0;
}
<img class="selectable" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" />
<img class="selectable" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" />
It works by toggling class named selected on click for every element with class selectable. Also, it will let you select multiple items.
If you want to limit the user to selecting only one element though, change the above JavaScript to:
function select(element) {
element.onclick = function() {
var selected = document.getElementsByClassName('selected')[0];
if (typeof selected !== 'undefined') { selected.classList.remove('selected'); }
if (element !== selected) { element.classList.add('selected'); }
}
}
Array.from(document.getElementsByClassName('selectable')).forEach(select);
You may use jQuery here for hovering effects, jQuery provides the hover() pseudo-event, which behaves better than moueseenter/mouseleave. Also, it's a good idea to create a CSS class for each state (normal and hovered), and then change the class on hover:
$(document).ready(function() {
$(".my_image_clas").hover(
function() { $(this).addClass("Hover"); },
function() { $(this).removeClass("Hover"); }
);
});
.my_image_clas.Hover { border: 3px solid blue; }
#Francesco Monti I've read your comment.
for working with jquery you may add jquery.js under the head tag of your html
<head>
<script src="jquery-1.12.0.min.js"></script>
</head>
or adding online would be
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
and you can use $(document).ready(function() under the script tags.
If you want you can separate js & css files and includes those files accordingly.
Your approx CSS:
.item {
box-sizing: border-box;
border: 2px solid transparent;
}
.item.selected,
.item:hover,
.item:focus {
border: 2px solid blue;
}
Some basic jQuery:
$('.item').on('click', function (event) {
event.preventDefault(); // Prevent default behavior if .item is a link or button
$(this).toggleClass('selected');
})

Link Changes Color On Multiple Hovers

I was wondering how it may be possible to change the text color of my anchor multiple times, different colors each time said anchor is hovered over. I have scoured the internet and StackOverflow, and this has to be the closest thing I came to:
http://www.codecademy.com/es/donvomar/codebits/xIEpDx
That link bears the same general idea of hovering over something multiple times and it changing color each time.
I did take a look at the code, but thought of two things to fix: one, I am not familiar with jQuery, but minimally with JS; and two, that I want to specify my colors; I noticed his were random. To give you a picture, here's my code just for the (empty) link and its styling:
<!DOCTYPE html>
<html>
<body>
<div class = "menu">Text block for demonstration</div>
<style>
.menu {
font-family: Bebas Neue, Helvetica, Arial, sans-serif;
font-size: 1.5em;
color: white;
padding: 10px;
border: 1px solid black;
width: 300px;
clear: both;
background-color: black;
}
</style>
</body>
</html>
To sum it all up: Basically, I want the text to change color each time it is hovered over, be able to specify the colors, and loop them.
Try this:
HTML
hello world!
JS
var arr = ['#f00', '#0f0', '#00f']; // Just add more if you like
var i = 0;
var start_over = arr.length;
$("#test").mouseenter(function(){
i++;
if (i == start_over) {
i = 0;
}
$(this).css('color', arr[i]);
});
JSFiddle
http://jsfiddle.net/V7qGx/
onmouseover = function() {
this.style.color = colors[this.dataset.n++ % colors.length];
}
onmouseout = function() {
this.style.color = '';
}

jQuery changing the background colour of a div depending on its current colour

Im new to jQuery and have been researching and playing with it as much as possible my issue is im running out of time i need to get this project done asap. Anyways my question...
I have a link when clicked it calls a jquery ajax function which is al working properly... upon success i want the code to change the background colour of a div but this depends on its current colour cause it can be switched back and forth between two colours...
anyways heres what ive been playing with...
highlightColor = "#d8fe00"; //Updated to not cause confusion...
whiteColor = "#ffffff"; //Updated to not cause confusion...
$("input[value*='" + cId + "']").closest("div[class*='link-black']").attr("background-color", function(iPos, color) {
if(color != highlightColor) { return highlightColor; }
else { return whiteColor; }
}
Any help would be appreciated thanks in advance!!
Consider using .toggleClass instead:
CSS:
.highlight { background-color: 'yellow'; }
JS:
$("#selector").toggleClass("highlight");
How about not styling with javascript and taking advantage of good ol' CSS?
CSS
.white { background-color: white; }
.white.highlight { background-color: yellow; }
.red { background-color: red; }
.red.highlight { background-color: pink; }
JS
$("input[value*='" + cId + "']").closest("div[class*='link-black']").toggleClass('highlight');
.classOne { color: red; }
.classTwo { color: blue; }
.classThree { color: green; }
.classOne.highlighted { background-color: white; }
.classTwo.highlighted { background-color: black; }
.classThree.highlighted { background-color: purple; }
In the AJAX callback, all you have to do is add the "highlighted" class to your element. You can let the CSS figure out which color the text is and which color the background should be. The classes should obviously be more descriptive than classOne though.

Categories

Resources