Removing JavaScript behavior - javascript

I need to remove the JavaScript behavior that I set on a div.
First, I set the CSS (it's an simple example) :
#redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
#redBloc:hover {
background-color: #3270ad;
}
Okay, for some reasons I need to override the behavior when the mouse is over my div.
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
It works like I want.
But later in my process, I need to reset the JavaScript behavior, to retrieve the behavior written in my CSS file.
How can I do this ?
Thank you
EDIT
I didn't need to override the behavior on the onmouseleave event, but later in my code, by the press of a button "disable behavior" for example.
That was solved by the solution of #T.J.Crowder.
Thank you all !

I think you mean you want to remove the specific background color so that the one from CSS can show through again (rather than "behavior").
If so, assign "" to it:
theElement.style.backgroundColor = "";
If you really do mean behavior and you don't want that mouseover handler to fire anymore, since you've used onmouseover to assign it, you can remove it by assigning null:
theElement.onmouseover = null;

Make your element null on mouseout, like:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseout = function() {
this.style.backgroundColor = '';
};
Have a look at the snippet below:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseout = function() {
this.style.backgroundColor = '';
};
#redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
#redBloc:hover {
background-color: #3270ad;
}
<div id="redBloc"></div>
Hope this helps!

You can remove the effect when user leaves your element using onmouseleave & null the style attribute:
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.style.backgroundColor = 'red';
};
redBloc.onmouseleave = function() {
this.style.backgroundColor = "";
};
<span id="redBloc">Hover me & leave me!</span>

You need to remove the style attribute by running the this code
var redBloc = document.getElementById('redBloc');
redBloc.removeAttribute('style')
You can have functionality on onmouseleave
redBloc.onmouseleave = function(){
this.removeAttribute('style');
}

You want to give redBloc the style with id #redBloc defined in Your css ... What You can do is create a css class and put all the styles in it that you want to apply on redBloc
.redBloc {
width: 100px;
height: 50px;
background-color: #ad3232;
}
then in your javascript you can add this class to redBloc on mouseover
var redBloc = document.getElementById('redBloc');
redBloc.onmouseover = function() {
this.className += " redBloc";
};
and this will add those styles defined in redBloc css class on your redBloc div. Hope this helps !

Related

How to select a new added element and edit it?

I have an <a> element:
<a id='addNewElementk' onclick='//Some Js Code' class='continueButton'>Click To Add</a>
When this anchor is clicked , A new element added:
New Added Element
And the first anchor which was clicked , Is removed.
I want to select that new element.
I tried:
window.onload = function(){
var newElem = document.getElementsByClassName('continueButton')[1];
alert(newElem.innerHTML);
}
I'm using ('continueButton')[1] , As there is another input with the same class before that anchor.
But for sure I get Click To Add from the first one , As that's was found when the page is loaded.
So how can I select that new element?
You're attempting to select the element before it exists in the DOM.
You instead need to run that code within the click event handler of the first <a>, like this:
window.onload = function() {
document.querySelector('#addNewElementk').addEventListener('click', function(e) {
e.preventDefault();
var a = document.createElement('a');
a.textContent = 'New Added Element';
a.href = '#';
a.classList.add('continueButton');
a.addEventListener('click', function(e) {
console.log(a.innerHTML);
});
this.parentNode.insertBefore(a, this);
this.remove();
});
}
<a id='addNewElementk' href="#" class='continueButton'>Click To Add</a>
Note the use of addEventListener() over the outdated on* event attributes which should be avoided.
You are attempting to select on an element that doesn't exist in the DOM. Dynamically added elements can be accessed in a couple of ways, above someone has an answer that adds an event listener to the created element which is a solid solution. The other most common way would be to use event delegation (if you are familiar with jQuery that would be $(parentElement).on('action', 'elementWeWantToWatch', function)) in Vanilla js the pattern is effectively the same, find or make a container element for your dynamic html, then add a listener to that container. Inside the listener you will want to ensure the target matches whatever your dynamic selection would be and execute when you find a match.
In this Example
The event listener is initiated on page load to watch the container element. The listener watches for clicks on elements with the continueButton class and when it finds one it removes the clicked element and adds a new element (the counter is to demonstrate that new content is being displayed :D)
(function() {
let i = 1;
const makeButton = () => {
const a = document.createElement('a');
a.classList.add('continueButton');
a.href = '#';
a.textContent = `Button ${i}`
i++;
return a;
}
const init = () => {
const container = document.querySelector('.test');
container.addEventListener('click', e => {
if (e.target.classList.contains('continueButton')) {
let button = makeButton();
container.appendChild(button);
container.removeChild(e.target);
return;
}
});
};
if (document.readyState == 'loading') {
window.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})()
.test {
width: 100%;
display: block;
text-align: center;
}
.continueButton {
display: block;
color: white;
background-color: green;
border-radius 2px;
padding: 15px 30px;
line-height: 2;
margin: 50px auto;
width: 200px;
text-decoration: none
}
<section class="test">
<a id='addNewElementk' class='continueButton'>Click To Add</a>
</section>

javascript .style property of span tag in anchor tag not working as expected

I am trying to style some buttons for my website
This is my html
<div>
<a class="page_numbers"><span>100</span></a>
<a class="page_numbers"><span>2</a></span></div>
this is my css
.page_numbers{
display:table-cell;
border:solid;
padding:0px;
border-radius:100px;
width:50px;
height:50px;
text-align:center;
vertical-align:middle;
}
div {
display:table;
border-spacing:10px;
}
}
and finally this is my javascript
var obj=document.getElementsByClassName("page_numbers")
for (i in obj){
console.log(obj[i].children)
obj[i].children[0].style.color="black"
obj[i].style.borderColor="rgb(85,170,255)"
function jun(i){
obj[i].addEventListener('mouseenter',function(){obj[i].style.background="yellow";obj[i].style.color="red"},true)
//
obj[i].addEventListener('mouseleave',function(){
obj[i].style.background="white";
obj[i].style.color="rgb(12,31,22)";},true)
}
jun(i);
}
the background color changes on mouseleave and enter but not the font color...I suppose I am doing something wrong along the way or I am missing a fundamental concept
this is my jsfiddle link
http://jsfiddle.net/repzeroworld/boqv8hak/
advice please..still learning JS
Firstly, all of this should be in CSS and is trivial to do so
.page_numbers:hover
{
background-color: yellow;
}
.page_numbers:hover span
{
color: red;
}
Now the issue you are having is that on about the 4th line of your JS you explicitly set the color of the child element (the span) inside the .page_number element to be black. Now on you mouse enter you are setting the color on the page_number element, but since the child has a style applied directly to it (i.e. color: black) it does not inherit the parent style. Inline styles (i.e. style applied directly to the element with the style="" attribute, which is what JS does) always have the highest precedence. This is why it is generally not best practice to put inline styles on an element, as you have just seen, they are pretty much impossible to override. So change either the child to not have an explicit style, or on the mouse enter change the child not the parent
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].children[0].style.color = "black"
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].children[0].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].children[0].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
or
var obj = document.getElementsByClassName("page_numbers")
for (i in obj) {
console.log(obj[i].children)
obj[i].style.borderColor = "rgb(85,170,255)"
function jun(i) {
obj[i].addEventListener('mouseenter', function () {
obj[i].style.background = "yellow";
obj[i].style.color = "red"
}, true)
//
obj[i].addEventListener('mouseleave', function () {
obj[i].style.background = "white";
obj[i].style.color = "rgb(12,31,22)";
}, true)
}
jun(i);
}
but as I indicated all this should really be in CSS
You trying to change color of a instead of span
Try like this
obj[i].children[0].style.color = "red"
JSFIDDLE

How to temporarily modify the CSS of an element

I am adding a CSS rule to an element with jQuery. E.g. $('#any-el').css('outline', '1px solid red').
I later remove the style with $('#any-el').css('outline', '').
I don't want to disturb any other styles this element may have, and I've found that this method works well for CSS added with external or inline stylesheets, but it will (obviously) modify and then remove any 'outline' given added via JavaScript at any previous point.
What is the best way to ensure that the value of the 'outline' style attribute is restored to the way it was before I modified it?
Here is the whole relevant part of the code:
var last_el = null
$('#mask').mousemove(function(e) {
var mask = $(this).detach()
var el = window.document.elementFromPoint(e.clientX, e.clientY)
if (el != last_el) {
if (last_el) {
$(last_el).css('outline', '')
}
if (el) {
$(el).css('outline', '1px solid red')
}
last_el = el
}
$('body').append(mask)
})
(Basically the #mask overlays the whole page and I outline the element which the mouse is hovering over, underneath the mask.)
You could store the value of the previous outline style in a variable before changing it, and then later restore the value of the variable. E.g.
var last_el = null;
var outline_style = null;
$('#mask').mousemove(function(e) {
var mask = $(this).detach();
var el = window.document.elementFromPoint(e.clientX, e.clientY);
if (el != last_el) {
if (last_el) {
$(last_el).css('outline', outline_style);
}
if (el) {
outline_style = $(el).css('outline');
$(el).css('outline', '1px solid red');
}
last_el = el;
}
$('body').append(mask);
});
The simplest thing you could do to add styles and restore them without any disturbance would be to put your new styles in a class and add/remove that class rather than setting inline styles. Make sure that all styles within the class are made !important.
var $span = $('span');
$('button').click(function () {
var $this = $(this),
override = $this.text() === 'Override';
$span.toggleClass('outline-override');
$this.text(override? 'Restore' : 'Override');
});
.outline-override {
outline: 1px solid red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="outline: 1px solid black;">test</span>
<button>Override</button>

.show(): how to call .show() on a specific element

I fixed my code but I'm having glitchy behavior. Specifically, when the mouse is no longer on the 'td.component' the buttons should be hidden but upon moving the mouse really fast over the various 'td.component's, some of these elements still show the buttons. Any thoughts on how I could fix this?
Thanks.
Code below:
$(function() {
var $newButton = $('<button class = "new"><img class = icon src = "images/new.png" >new</img></button>');
var $deleteButton = $('<button class = "delete"><img class = icon src = "images/delete.png" >delete</img></button>');
var $saveButton = $('<button id = "save">Save</button>');
for (i = 42; i > 0; i--) {
$table.append('<tr><td class = "number">' + i +
'</td><td class = "component"></td></tr>');
}
//appends to all 'td.component'
$('td.component').append($newButton).append($deleteButton);
//hides all buttons
$('button.new').hide();
$('button.delete').hide();
$('td.component').mouseover(function(e) {
$(this).find('button.new').show();
$(this).find('button.delete').show();
});
$('td.component').mouseout(function(e) {
$(this).find('button.new').hide();
$(this).find('button.delete').hide();
});
$('button.new').mouseout(function(e) {
e.stopPropagation();
});
$('button.delete').mouseout(function(e) {
e.stopPropagation();
});
});
You can use find:
$('td.component').mouseover(function(e) {
$(this).find('button.new').show();
$(this).find('button.delete').show();
});
Here is a jsfiddle.
You'll probably want to hide the buttons once the mouse leaves.
As #elzi pointed out, if you just want to show/hide them on hover, you are best off using CSS hover:
td.component button {
display: none;
}
td.component:hover button {
display: inline;
}
(classes ignored for simplicity)
Updated jsfiddle.
You can use this to execute the set of functions on that element.
$('td.component').mouseover(function(e) {
$(this).find('button.new').show();
$(this).find('button.delete').show();
});
This would find the buttons inside that particular element.

Function that adds a div of a particular class

In my CSS I have a particular class for a div
div.videl
{
width: 80%;
margin: 0 auto;
background-color: #39275b;
color: white;
padding: 5px;
}
and then a function to add divs of that class:
this.addVideo = function()
{
var newVidElement = document.createElement("div");
newVidElement.class = "videl";
newVidElement.innerHTML = "<p>(" + ++this.numVids + ") <textarea class='vidtxt'></textarea></p>"
document.getElementById("vidplaydiv").appendChild(newVidElement);
}
However, for some reason, that function is not correctly applying the CSS properties when I test it out. See this page http://jaminweb.com/YoutubePlaylist.html and click the Add Another Video button. Any idea what I'm doing wrong?
className is the name of the attribute you're trying to set.
newVidElement.className = "videl";
When you don't know the property name of the HTML attribute, You can always use setAttribute, for example:
newVidElement.setAttribute('class','videl')
Change the JavaScript code as below -
this.addVideo = function()
{
var newVidElement = document.createElement("div");
newVidElement.className = "videl";
newVidElement.innerHTML = "<p>(" + ++this.numVids + ") <textarea class='vidtxt'></textarea></p>"
document.getElementById("vidplaydiv").appendChild(newVidElement);
}

Categories

Resources