Reset Dom element to initial state (jquery/javascript) - javascript

So i am trying to add a couple of css classes (red and shrink) on mouseover and mouseout. I have successfully done that but once I move my mouse out of the container or area of focus, the shrink class still remains.
How can I reset all classes back to the original state?
Here is the code i have so far:
var lis = $('.list');
lis.on('mouseover mouseout', changeColor);
function changeColor (e) {
$el = e.currentTarget;
if( e.type == 'mouseover') {
$el.classList.add('red');
$el.classList.remove('shrink');
} else if (e.type == 'mouseout'){
$el.classList.remove('red');
$el.classList.add('shrink');
}
else {
$el.classList.remove('red');
$el.classList.remove('shrink');
}
}
Thank you.

This might work.
var lis = $('.list');
lis.on('mouseover mouseout', changeColor);
function changeColor (e) {
$el = e.currentTarget;
if( e.type == 'mouseover') {
$el.classList.add('red');
$el.classList.remove('shrink');
} else if (e.type == 'mouseout'){
$el.classList="list";
}
}
.list
{
height:50px;
width:50px;
background:green;
}
.red
{
background : red;
}
.shrink
{
background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>

Refactored the code using pure jQuery. works as expected.
var lis = $('.list');
lis.hover(function(e){
e.preventDefault();
$(this).toggleClass('red')
.siblings(lis).toggleClass('shrink');
});

Related

Javascript keydown event twice to cancel

My intention is to make div when keydown, and remove div when the same key is pressed again.
This is my code.
let keydown = false;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
if (!keydown) {
keydown = true;
console.log("space")
e.preventDefault(); //space doesn't manipulate position
$("body").append($("<div id='refactor'></div>"))
$(refactor).append($(".highlight").text())
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
What should I do to remove the div when Space is hit again?
First of all...jquery...avoid this bloatware by all means, please...
Of course this is based on what you've asked here, but I'd recommend instead of store true/false for the pressed key, store the new div element instead. This way, you'll have instant access to it without need search in the DOM.
To remove a node from the DOM, you just need execute node.removeChild(child)
let div = null;
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div)
{
//remove div from DOM
div.parentNode.removeChild(div);
div = null;
}
else
{
//create new div
div = document.createElement("div");
div.id = "refactor";
div.textContent = document.querySelector(".highlight").textContent;
document.body.appendChild(div);
}
}
})
#refactor
{
background-color: lightgreen;
}
<div class="highlight">test</div>
If your whole goal is to show/hide an element, than you should do so via CSS instead of adding/removing elements from DOM, it's significantly faster and allows add additional animations/styles:
let div = document.getElementById("refactor");
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
console.log("space")
e.preventDefault(); //space doesn't manipulate position
if (div.classList.contains("hidden"))
{
div.textContent = document.querySelector(".highlight").textContent + " " + Date();
}
div.classList.toggle("hidden");
}
})
#refactor
{
background-color: lightgreen;
transition: height 0.5s, width 0.5s, background-color 0.5s;
height: 1.5em;
width: 100%;
overflow: hidden;
}
#refactor.hidden
{
height: 0;
width: 0;
background-color: pink;
}
<div class="highlight">test</div>
<div id="refactor" class="hidden"></div>
<div>blah</div>

Make appended children to also trigger parent element

I have appended 2 buttons for each li element in my app:
todoLi.appendChild(this.createToggleButton());
todoLi.appendChild(this.createDeleteButton());
Later, I added event listeners to trigger when li is moused over and out
todosUl.addEventListener('mouseover', function(event) {
let elementMousedOver = event.target;
if(elementMousedOver.className == 'todoLi') {
elementMousedOver.lastElementChild.style.display = 'inline';
}
});
todosUl.addEventListener('mouseout', function(event) {
let elementMousedOver = event.target;
if(elementMousedOver.className == 'todoLi') {
elementMousedOver.lastElementChild.style.display = 'none';
}
});
Everything works fine for li element, but when I mouse over the buttons, that are children of the li element, event listeners stop working for some reason if the bottons were not children of li element after all.
How can I make appended children to also trigger its parent's event listener?
Here is my app on github: https://mikestepanov.github.io/
repo with files: https://github.com/mikestepanov/mikestepanov.github.io
Events by default are bubbling up the DOM, therefore the event triggered from the li will trigger the ul as well, the issue is that your if statement will handle only the cases in which the event's target is the ul (className == "todoLi")
var todosUl = document.getElementsByClassName("todo")[0];
todosUl.addEventListener('mouseover', function(event) {
let eOver = event.target;
if(eOver.className == 'todo') {
//for the ul
console.log("I'm handeled from " + eOver.className);
} else if (eOver.className == 'item') {
//for the li
console.log("I'm handeled from " + eOver.className);
}
});
todosUl.addEventListener('mouseout', function(event) {
let eOver = event.target;
if(eOver.className == 'todo') {
//for the ul
console.log("I'm handeled from " + eOver.className);
} else if (eOver.className == 'item') {
//for the li
console.log("I'm handeled from " + eOver.className);
}
});
ul{
padding: 15px;
background: lightblue;
}
li{
background: grey;
padding: 5px 5px;
}
<ul class="todo">
<li class="item">Do it!!</li>
</ul>
The problem here lies with the conditional statement. Simply modify your conditional statement to include the button element and it should work.
todosUl.addEventListener('mouseover', function(event) {
let elementMousedOver = event.target;
if(elementMousedOver.className == 'todoLi' ||
elementMousedOver.tagName === "BUTTON") {
elementMousedOver.lastElementChild.style.display = 'inline';
}
});

Click outside element without using event.stopPropagation

I know there are lots of ways to detect the click outside of an element. Mostly all of them use event.stopPropagation. Since event.stopPropagation will break other stuff, I was wondering if there is another way to achieve the same effect. I created a simple test for this:
HTML:
<div class="click">Click me</div>
Javascript:
$(function() {
var $click = $('.click'),
$html = $('html');
$click.on( 'click', function( e ) {
$click.addClass('is-clicked').text('Click outside');
// Wait for click outside
$html.on( 'click', clickOutside );
// Is there any other way except using .stopPropagation / return false
event.stopPropagation();
});
function clickOutside( e ) {
if ( $click.has( e.target ).length === 0 ) {
$click.removeClass('is-clicked').text('Click me');
// Remove event listener
$html.off( 'click', clickOutside );
}
}
});
http://jsfiddle.net/8p4jhvqn/
This works, but only because i stop the bubbling with event.stopPropagation();. How can i get rid of event.stopPropagation(); in this case?
It can be done in a simpler way, can't it be? Why complicate things when something as simple as below could work.
$(document).click(function(e){
var elm = $('.click');
if(elm[0] == e.target){
elm.addClass("is-clicked").text("click outside");
} else { elm.removeClass("is-clicked").text("click inside"); }
});
DEMO
You could do something like this to achieve the same effect
$(document).on("click", function(e){
var target = $(e.target);
if(target.hasClass("click")){
$click.addClass('is-clicked').text('Click outside');
}else{
$click.removeClass('is-clicked').text('Click me');
}
});
HTML code:
<div id="box" style="width:100px; height:100px; border:1px solid #000000; background-color:#00ff00;"></div>
JavaScript code:
function Init()
{
$(document).click(function(event){
if(event.target.id == "box")
{
$(event.target).css("backgroundColor", "#ff0000");
}
else
{
$("#box").css("backgroundColor", "#00ff00");
}
})
}
$(document).ready(Init);
If the element in question has child elements, then those may show up as e.target, and you can't simply compare it to your element.
In that case, capture the event in both the event and in the document, and detect events which only occurred on the document, for example by recording and comparing e.target:
var lastTarget = undefined;
$("#interesting-div").click(function(e) {
// remember target
lastTarget = e.target;
});
$(document).click(function(e) {
if (e.target != lastTarget) {
// if target is different, then this event didn't come from our
// interesting div.
// do something interesting here:
console.log("We got a click outside");
}
});
var lastTarget = undefined;
$("#interesting-div").click(function(e) {
// remember target
lastTarget = e.target;
});
$(document).click(function(e) {
if (e.target != lastTarget) {
// if target is different, then this event didn't come from our
// interesting div.
// do something interesting here:
console.log("We got a click outside");
}
});
#interesting-div {
background: #ff0;
border: 1px solid black;
padding: .5em;
}
#annoying-childelement {
background: #fa0;
border: 1px solid black;
margin: 1em;
padding: .5em;
width: 20em;
}
#large-div {
background: #ccc;
padding: 2em 2em 20em 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="large-div">
<div id="interesting-div">
This is our interesting element
<div id="annoying-childelement">
child element
</div>
</div>
</div>
</div>

After initial click, have to click twice with Jquery click()

Couldn't find a solution that actually worked, but I want that on a click, a div shows.
Now this works when I load the page, but then after that first click, I have to click twice every time for the div to show.
Any ideas?
$(document).ready(function () {
setMenu();
});
function setMenu()
{
var headerExtIsOpen = false;
$('#headerExt').hide();
$('#header').click(function () {
if (!headerExtIsOpen) {
$('#headerExt').show();
headerExtIsOpen = true;
} else {
$('#headerExt').hide();
headerExtIsOpen = false;
}
});
}
There is no need to remember the state, just use toggle()
$(function () {
setMenu();
});
function setMenu()
{
$('#headerExt').hide();
$('#header').on("click", function (e) {
e.preventDefault();
$('#headerExt').toggle();
});
}
You said you want to toggle other things.
Best thing would be to toggle a class to change the color
$('#header').on("click", function (e) {
e.preventDefault();
$(this).toggleClass("open");
$('#headerExt').toggle();
});
another way is to check the state
$('#header').on("click", function (e) {
e.preventDefault();
var child = $('#headerExt').toggle();
var isOpen = child.is(":visibile");
$(this).css("background-color" : isOpen ? "red" : "blue" );
});
if the layout is something like
<div class="portlet">
<h2>Header</h2>
<div>
<p>Content</p>
</div>
</div>
You can have CSS like this
.portlet h2 { background-color: yellow; }
.portlet > div { display: none; }
.portlet.open h2 { background-color: green; }
.portlet.open > div { display: block; }
And the JavaScript
$(".portlet h2 a").on("click", function() {
$(this).closest(".portlet").toggleClass("open");
});
And there is layouts where it would be possible to have zero JavaScript involved.
Turns out I had some script hidden in my .js file that closes the menu again when the user clicks elsewhere, that I forgot about.
function resetMenu(e) {
var container = $('#headerExt');
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$('#header').css("background-color", "inherit");
container.hide();
headerExtIsOpen = false;
}
}
I forgot to set the headerExtIsOpen back to false again after closing it in this function (code above shows the fix). Now it works fine :)

How to set toolbar inside element while hovering that HTML element using JQuery?

$('body').on('mouseover mouseout', '*:not(.printToolBar)', function (e) {
if (this === e.target) {
(e.type === 'mouseover' ? setMenuBox(e.target) : removeMenuBox(e.target));
}
});
function setMenuBox (obj){
$(obj).wrap('<div class="toolBarWrapper" style="position:relative;"/>');
$(".toolBarWrapper").append($('.printToolBar'));
}
function removeMenuBox (obj){
$(".toolBarWrapper").remove('.printToolBar');
$(obj).unwrap();
}
function createToolBar(){
var ul = $("<ul>").attr({
'class': "printToolBar",
style: "border: 1px solid #ff0000; position:absolute; top:0 ; right: 0;"
});
var li = $("<li>").attr({
'className': "printToolBarList"
}).text('Print');
var printLi = li.clone().attr({
id: "print"
}).on('click',function(e){
console.log(this);
});
ul.append(printLi).appendTo("body");
};
createToolBar();
This is what I am trying to do set the menubar with every HTML element, but I am unable to detach the event on menubar it self, which is causing problem by throwing some JS error, is there any other way to achieve the same?
To remove the 'hover' behavior on the ul element, I think you need to update your first code line :
$('body').on('mouseover mouseout', '*:not(.printToolBar), *:not(ul)', function (e) {
if (this === e.target) {
(e.type === 'mouseover' ? setMenuBox(e.target) : removeMenuBox(e.target));
}
});
This way you will attach mouseevent to all elements but ul and .printToolbar
EDIT :
To remove attachments of UL children :
$('body').on('mouseover mouseout', '*:not(ul.printToolBar), *:not(ul.printToolBar > *)', function (e) {
if (this === e.target) {
(e.type === 'mouseover' ? setMenuBox(e.target) : removeMenuBox(e.target));
}
});

Categories

Resources