To make the effect work separately for each class (Javascript) - javascript

There are three classes named "main-menu."
I want to apply the effect that underlines when I raise the mouse cursor in the area corresponding to each class.
I know that the current target is in the 0th index of the class and I have to use variables, but I don't know how to change that to suit the situation.
I would appreciate it if you could tell me how to solve this problem.
window.onload = function(){
var target = document.getElementsByClassName("main-menu")[0];
target.addEventListener('mouseover', function(){
target.style.borderBottom = "5px solid black";
});
target.addEventListener('mouseout', function(){
target.style.borderBottom = "none";
});
}

Try adding mouse hover css instead
.main-menu:hover {
border-bottom: 5px solid black;
}

You can use loop and add effect to each element. You can do this with css as well
.main-menu:hover { border-bottom: 5px solid black; }
window.onload = function(){
var elements = document.getElementsByClassName("main-menu");
for(let index=0; index < elements.length;index++) {
const target = elements[index];
target.addEventListener('mouseover', function(){
target.style.borderBottom = "5px solid black";
});
target.addEventListener('mouseout', function(){
target.style.borderBottom = "none";
});
})
}

Related

How can I apply a event listener to an array of elements?

So I am trying to make a bookmarklet that when you hover over things, they light up, and this is what I have so far
var h1 = document.getElementsByTagName("h1");
h1length = h1.length;
for (var i=0; i <= h1.length; i++)
{
h1[i].addEventListener("mouseover", lightUp, false);
}
function lightUp()
{
h1[i].style.textShadow = "2px 2px 5px blue";
}
But this just doesn't do anything when I hover over the h1 element that I am using, can someone tell me what I am doing wrong if I add a () after the lightUp, it immediately runs the function without me hovering over.
Also, there is nothing wrong with the for loop, when I applied the text shadow without the hovering, it applied it to all h1 elements, it is something wrong with the listener I think.
Your lightUp function shouldn't rely on the i variable you're using to add the listeners for a variety of reasons. It should either get the h1 from the event, as in:
function lightUp(event) {
event.target.style.textShadow = "2px 2px 5px blue";
}
Or be bound when you add the listener, as in:
h1[i].addEventListener("mouseover", () => lightUp(h1[i]), false);
function lightUp(element)
{
element.style.textShadow = "2px 2px 5px blue";
}
After your for loop runs, the value of i is going to be h1.length + 1, so your lightUp function is always going to attempt to operate on a nonexistent h1. (I would expect this to throw an exception: attempting to access .style on undefined.)
I highly recommend switching from index-based looping to for...of instead, which is much more readable:
const headlines = document.getElementsByTagName("h1");
for (const headline of headlines) {
headline.addEventListener("mouseover", lightUp, false);
}
function lightUp(event) {
event.target.style.textShadow = "2px 2px 5px blue";
}
<h1>Foo</h1>
<h1>Bar</h1>
<h1>Baz</h1>

Removing JavaScript behavior

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 !

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>

Add id dynamically to each table cells

I am trying to create a dynamic js table and I want to give id to each cell dynamically. I want to use those ids to use in different js event handlers. How it can be done? I have tried in different ways but none of them works!
<html>
<head>
<style>
#colors {
float: right;
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<script>
var d;
var k = 0;
function makeit() {
var tbl = document.createElement("table");
var atts = document.createAttribute("style");
atts.value = "border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px;";
tbl.setAttributeNode(atts);
for (i = 0; i < 5; i++) {
var rows = tbl.insertRow(i);
for (j = 0; j < 7; j++) {
d = rows.insertCell(j);
d.height = "50px";
d.width = "50px";
d.style.backgroundColor = "yellow";
d.addEventListener("click", function myfunc() { d.style.backgroundColor = "red"; });
}
}
document.body.appendChild(tbl);
}
window.onload = makeit;
</script>
</body>
</html>
Just add
d.id = "r" + i + "c" + j;
under
d=rows.insertCell(j);
to set unique ids on each td.
Obviously, you can change the syntax r2c4 (which would be 3. row and the 5. cell) to your own liking.
If you want to call a function when clicking on a specific td you could even pass the row index (i) and column index (j) to that function.
Side note
You should consider using a JavaScript library or framework like jQuery for manipulations like this. It would facilitate your work a lot in the long term.
The problem is a scope issue. When adding the event listener, d's reference gets updated to be the last table cell you have created.
You can simply change the event listener's function to:
function myfunc() {
this.style.backgroundColor="red";
}
So that this references the object it is attached to. Depending on your intention, you may not need unique ids if you have access to the cell itself.
Using an approach that includes wongcode's solution, you may wish to consider the following code:
<html>
<head>
<style>
#myTbl{ border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px; }
#myTbl td{ width: 50px; height: 50px; background-color: yellow;}
</style>
</head>
<body>
<script>
function onCellClicked(e)
{
this.style.backgroundColor = 'red';
}
function makeit()
{
var tbl=document.createElement("table");
tbl.id = 'myTbl';
var curCellIndex = 0;
for(i=0;i<5;i++)
{
var rows=tbl.insertRow(i);
for(j=0;j<7;j++)
{
d=rows.insertCell(j);
d.id = 'cell_' + curCellIndex;
curCellIndex++;
d.addEventListener("click",onCellClicked, false);
}
}
document.body.appendChild(tbl);
}
window.onload=makeit;
</script>
</body>
</html>
Some of the advantages include:
Smaller html file created in your editor
Smaller html code created in the browser
Use of context and the this keyword
Smaller memory consumption, since each TD doesn't contain the full
body of the event handler (it only include a 'pointer' to the
function to be executed)
EDIT: forgot to add code to give the cells an id. Now fixed.

multiple onclick events on a single div - changing the div border colors - javascript

I've put this code inside the div:
onclick="this.style.border='solid 1px red';"
How to insert multiple onclick events which would trigger changes of border colors - for example 1st click - red, 2nd click - blue, 3rd click - reset?
This is exactly what I need - changes of the one particular div with multiple onclick events, not improvisations with multiple divs.
edit:
I also have other actions called with onclick + I have onmouseenter and onmouseleave events inside of the same div. Everything work as it should, I only can't get multiple onclick events to work.
I can't get any of these functions to work and I can't tell why. Maybe because I have more actions and events, or maybe it's up to Wordpress?
(I put a function in the header area inside of <script></script>)
I thought this will be easier than playing a sound, but surprisingly sounds were a piece of cake and this seems to be a real challenge...
can somebody help?
edit2: It was up to Wordpres. Now I know how to make proper functions to work.
edit3: I've edited a little solution posted by user1875968, and I finally got exactly what I want (with proper reset):
var linkClick = 1;
function update_link(obj){
if (linkClick == 1){obj.style.border = 'solid 1px red'};
if (linkClick == 2){obj.style.border = 'solid 1px blue'};
if (linkClick == 3){obj.style.border = 'solid 1px green'};
if (linkClick >3 ) {obj.style.border = 'solid 1px #555555'; linkClick=0};
linkClick++;
}
thanks everybody for your help ;)
you can make use of functions and css classes.
Identify the styles you want to switch between as different classes. Let's take them as:
.redBorder
{
border: 1px solid red;
}
.blueBorder
{
border: 1px solid blue;
}
.resetBorder
{
border: none;
}
declare a function on the click event of the div:
onclick="switchBorder(this);"
Inside the function, use a switch case on the div class:
function switchBorder(divObj)
{
prevClass = divObj.className;
switch( prevClass )
{
case 'redBorder':
divObj.className = "blueBorder"
break;
case 'blueBorder':
divObj.className = "resetBorder"
break;
case 'resetBorder':
divObj.className = "redBorder"
break;
}
}
Hope that helps. :)
Edit: syntax mistake.
<script>
var linkClick = 0;
function update_link(obj){
if (linkClick == 0){obj.style.border = 'solid 1px red'};
if (linkClick == 1){obj.style.border = 'solid 1px blue'};
if (linkClick >1 ) {obj.style.border = 'solid 1px red'; linkClick=0};
linkClick++;
}
</script>
HTML
<a href='#' onclick='update_link(this)'> my link </a>
The only way i could think of is changing the on-click event every time it's fired like:
x.onclick = method1;
function method1()
{
x.onclick = method2;
}
funbction method2()
{
x.onclick = method3;
}
function method3()
{
x.onclick = method1;
}
You can make use of integers
onclick="my_function()"
and then:
function my_function(){
i++;
if(i == 1){
//red
}
if(i == 2){
//blue
}
if(i == 3){
i = 0;
// reset
}
}
it's best to use javascript for this.
var clicks = 0;
function changeBorder() {
if(++clicks > 2) clicks = 1;
switch (clicks) {
case 1 : { this.style.border='solid 1px red';}; break;
case 2 : { this.style.border='solid 1px blue';}; break;
}
}
But you have to adapt on the "this" element. (i don't know which one it is, use getElementById)
and use in HTML,
onclick="changeBorder()"
Something like this. Presuming the default border is "1px solid black". This can be extended to contain as many changes and colors as you want.
function changeBorder(ele){
var colors = ["1px solid black", "1px solid red", "1px solid blue"];
var curInd = colors.indexOf(ele.style.border);
if(curInd != colors.length-1){ //If the current color isn't the last one
//Next color
ele.style.border = colors[curInd++];
} else {
//Reset to first color
ele.style.border = colors[0];
}
}
NOTE: array.indexOf is an ECMAscript 5 implementation for older browsers please include the shim found here
Try using a global variable like colorCode and initialize it to zero—colorCode=0
And call a function onClick="ChangeBGColor()"
function ChangeBGColor()
{
colorcode++;
var color='';
if (colorcode==1)
{
color='red';
}
else if (colorcode==2)
{
color='blue';
}
else
{
colorCode=0; /*Reset to zero if colorCode =3 or more*/
color='gray';
}
this.style.border="'solid 1px "+color+ "';" /* Need to correctly apply style for the specific contol*/
}
<div id="x" onclick="Clicked"></div>
<script type="text/javascript">
var clickno=1;
function Clicked()
{
if(clickno==1)
{
document.getElementById('x').style.border="solid 1px red";
}
if(clickno==2)
{
document.getElementById('x').style.border="solid 1px blue";
}
if(clickno==3)
{
document.getElementById('x').style.border="solid 1px red";
clickno=1;
}
clickno++;
}
</script>

Categories

Resources