how to click any element and target will switch to it - javascript

here is what i try to code
i want my mouse click on any element on page and target will boxshadow ,
and after i click the element i can click another element and the previus element will lost its boxshadow and i am using code like this
document.onclick = function(evt){
console.log('clicked');
var target = null,
target = evt.target;
var obj = document.querySelector(target);
obj.style.boxShadow = '3px 10px 100px yellow';
if(target === 'null'){
console.log('ye');
obj.style.boxShadow = '0';
obj = document.querySelector(target)
console.log(obj)}
return target}

Add element selector once you have applied css and select those elements using provided selector.
Remove applied css by selecting applied attribute.
document.onclick = function(evt) {
var target = evt.target;
var pastElems = document.querySelectorAll('.shadowed');
[].forEach.call(pastElems, function(el) {
el.style.boxShadow = 'none';
target.classList.remove('shadowed');
})
target.style.boxShadow = '3px 10px 100px yellow';
target.classList.add('shadowed');
}
.elem {
width: 100px;
height: 100px;
border: 1px solid black;
float: left;
}
<div class='elem'></div>
<div class='elem'></div>
<div class='elem'></div>
<div class='elem'></div>

It's easier to change styling by adding/removing classes.
If you use an object, it will allow you to keep track of what element currently has the shadow and remove the class from it.
var setBoxShadow = {
target: null,
clearShadow: function() {
if (this.target != null && this.target != undefined) {
this.target.classList.remove("highlight");
}
},
addShadow: function(newTarget) {
this.target = newTarget;
this.target.classList.add("highlight");
},
}
body.onclick = function(evt) {
setBoxShadow.clearShadow();
setBoxShadow.addShadow(evt.target);
}
And the CSS:
.highlight {
box-shadow: 3px 10px 100px yellow;
}

Related

How Can Conflict Between Mouse Events Be Resolved

I have a div called starter-box that when clicked is supposed to dynamically create 2 divs. I added an event listener to the parent of the starter-box div to listen for any event of the 2 dynamically created divs.
The problem is that the click event listener conflicts with the mousedown event listener preventing it (the click event) from executing.
document.addEventListener('DOMContentLoaded', function () {
var container = document.querySelector("#container");
var target;
var elementCreated = false;
var elements = [];
container.addEventListener("click", (ev) => {
target = ev.target;
if (target.className != "box" && target.id != "container") {
if (elementCreated == false) {
createElements(target);
} else if (elementCreated == true) {
removeElementsByClass("box");
elements = [];
}
}
});
container.addEventListener("mousedown", (ev) => {
target = ev.target;
alert("MouseDown on: " + target.id);
});
container.addEventListener("mouseup", (ev) => {
target = ev.target;
alert("MouseUp on: " + target.id);
});
function createElements(target) {
const dimensions = target.getBoundingClientRect();
const element1 = document.createElement('div');
element1.className = "box";
element1.id = "box1";
element1.style.left = (dimensions.left) + "px";
element1.style.top = dimensions.bottom + 25 + "px";
container.appendChild(element1);
const element2 = document.createElement('div');
element2.className = "box";
element2.id = "box2";
element2.style.left = (dimensions.left) + "px";
element2.style.top = dimensions.bottom + 90 + "px";
container.appendChild(element2);
}
});
#container {
width: 600px;
height: 400px;
background-color: blue
}
#starter-box {
position: relative;
top: 50px;
left: 25px;
width: 50px;
height: 50px;
background-color: red
}
.box {
position: absolute;
width: 50px;
height: 50px;
background-color: black
}
<div id="container">
<div id="starter-box">
</div>
</div>
Check the fields of event object (ev argument to the listener callback).
In case of 'click' event: ev.type === 'click'
In case of 'mousedown' event: ev.type === 'mousedown'
You can use it your logic.
Discover the event object, try to console.log(ev), and see. There are more differences.

Uploading a text file and drag and drop the words?

I'm uploading a text file into my homepage and it's currently loading into a text area.
The issue is I want to drag and drop individual words into a different html element which I don't think is possible from text area elements in html?
Is there a way around this with html or JavaScript?
I would suggest you to create draggable elements for each of the words once you upload the file:
<span class="word" draggable="true">word</span>
So then you could apply the standard HTML5 drag and drop behavior on these span elements. Check out the example below:
const words = 'words from file';
const container = document.getElementById('container');
let dragged;
container.innerHTML = words.split(' ').map(w => `<span class="word" draggable="true">${w}</span>`).join('');
function onDragOver(event) {
// Prevent default to allow drop
event.preventDefault();
}
function onDragLeave(event) {
event.target.style.background = '';
}
function onDragEnter(event) {
const target = event.target;
if (target && dragged && target.classList.contains('drop-zone')) {
event.preventDefault();
// Set the dropEffect to move
event.dataTransfer.dropEffect = 'move'
target.style.background = '#1f904e';
}
}
function onDrop(event) {
const target = event.target;
if (target && dragged && target.classList.contains('drop-zone')) {
target.style.backgroundColor = '';
event.preventDefault();
// Get the id of the target and add the moved element to the target's DOM
dragged.parentNode.removeChild(dragged);
dragged.style.opacity = '';
target.appendChild(dragged);
}
}
function onDragStart(event) {
dragged = event.target;
event.dataTransfer.setData('text', event.target.id);
event.dataTransfer.dropEffect = 'move';
// Make it half transparent
event.target.style.opacity = .3;
}
function onDragEnd(event) {
// Reset the transparency
event.target.style.opacity = ''; // reset opacity when drag ends
dragged = null;
}
for (word of document.getElementsByClassName('word')) {
word.addEventListener('dragstart', onDragStart);
word.addEventListener('dragend', onDragEnd);
}
for (dropZone of document.getElementsByClassName('drop-zone')) {
dropZone.addEventListener('drop', onDrop);
dropZone.addEventListener('dragenter', onDragEnter);
dropZone.addEventListener('dragleave', onDragLeave);
dropZone.addEventListener('dragover', onDragOver);
}
.drop-zone {
position: relative;
width: 100px;
height: 30px;
overflow: hidden;
background: #878787;
color: white;
display: flex;
align-items: center;
justify-content: center;
margin: 5px 0;
}
.word {
margin: 0 2px;
}
<div id=container></div>
<div class='drop-zone'></div>
<div class='drop-zone'></div>
<div class='drop-zone'></div>

Unable to remove an event listener

Ok so I have a div with an animation:
var x = true;
function dynamicTaskbar(thumb) {
function anim1() {
thumb.style.backgroundColor = "green";
}
function anim2() {
thumb.style.backgroundColor = "blue";
}
if (x === false) {
thumb.style.backgroundColor = "red";
thumb.removeEventListener("mouseover", anim1);
thumb.removeEventListener("mouseleave", anim2);
x = true;
} else {
thumb.style.backgroundColor = "blue";
thumb.addEventListener("mouseover", anim1);
thumb.addEventListener("mouseleave", anim2);
x = false;
}
}
//Create window's thumbnail for taskbar
var thumbnail = document.createElement("div");
thumbnail.setAttribute("class", "thumbnail");
taskbar.append(thumbnail);
taskbar.style.width = taskbar.style.width + thumbnail.style.width + "px";
thumbnail.addEventListener("mousedown", function() {
dynamicTaskbar(thumbnail);
});
#taskbar {
background-color: red;
border: solid 1px black;
width: 50px;
height: 30px;
}
.thumbnail {
width: 50px;
height: 30px;
border: solid 1px black;
}
<div id="taskbar"></div>
By default, the div is red.
When it is clicked:
If x is true, it becomes false and the div turns blue. Two event listeners, mouseover (the div becomes green) and mouseleave (the div becomes red again) are added.
If x is false, it becomes true and the div turns red. But here is my problem: both event listeners (mouseover and mouseleave) are suppose to be removed, but it doesn't work. I searched over the Internet but found nothing that fixed my problem.
Any help?
The solution for this problem is extracting the anim1() and anim2() funtions from the dynamicTaskbar() function.
Since both functions are located inside the dynamicTaskbar() function they are created again and again with each execution of the function causing the instances to be different then the initial ones.
If for example in the first execution (1st click) of dynamicTaskbar() the "object id" of anim1() will be "1" and in the second execution it will be "2". Therefore when you're trying to remove the listener you're actually trying to remove it for a different object reference.
Take a look at the example:
var x = true;
function anim1(thumb) {
thumbnail.style.backgroundColor = "green";
}
function anim2(thumb) {
thumbnail.style.backgroundColor = "blue";
}
function dynamicTaskbar(thumb) {
if (x === false) {
thumbnail.style.backgroundColor = "red";
thumbnail.removeEventListener("mouseover", anim1);
thumbnail.removeEventListener("mouseleave", anim2);
x = true;
} else {
thumbnail.style.backgroundColor = "blue";
thumbnail.addEventListener("mouseover", anim1);
thumbnail.addEventListener("mouseleave", anim2);
x = false;
}
}
//Create window's thumbnail for taskbar
var thumbnail = document.createElement("div");
thumbnail.setAttribute("class", "thumbnail");
taskbar.append(thumbnail);
taskbar.style.width = taskbar.style.width + thumbnail.style.width + "px";
thumbnail.addEventListener("mousedown", function() {
dynamicTaskbar(thumbnail);
});
#taskbar {
background-color: red;
border: solid 1px black;
width: 50px;
height: 30px;
}
.thumbnail {
width: 50px;
height: 30px;
border: solid 1px black;
}
<div id="taskbar"></div>

My hover popup is flickering and moving when it shouldn't

Trying to create a popup that will show when hovering over an element. However it flickers and moves around when I move my mouse inside the element. It should also stay open if the mouse moves over the popup.
Trying to do this without library cheats like jQuery. You don't learn if you use them.
If you hover your mouse over one of the tags below, that's exactly what I'm trying to create.
Think the error is somewhere in this code:
function showPopup(e) {
var popup = document.getElementById('popup');
if (popup.style.display == 'none') {
popup.style.display = 'block';
var bodyRect = document.body.getBoundingClientRect(),
elemRect = e.target.getBoundingClientRect(),
offsetX = elemRect.left - bodyRect.left,
offsetY = elemRect.bottom - bodyRect.top;
popup.style.left = offsetX + 'px';
popup.style.top = offsetY + 'px';
//console.log(e);
}
}
function hidePopup(/*e*/) {
setTimeout(function() {
var popup = document.getElementById('popup');
if (popup.style.display == 'block' && !window.inside_popup) {
popup.style.display = 'none';
window.inside_popup = false;
console.log('hide');
} else {
setTimeout(hidePopup, 50); // try a little later
}
}, 50); // Give the events ability to catch up and tell us the mouse is inside the popup
}
var targ = document.querySelector('ul li')
targ.addEventListener('mouseover', showPopup);
targ.addEventListener('mouseout', hidePopup);
Full javascript code with a real test element:
https://jsfiddle.net/g8wvae8o/
As #epascarello said, mouseleave and mouseenter are what you're looking for. There's no need for setTimeout here either. In addition, you're targeting every li on the page (is that intentional?) I recommend targeting a specific class of element to reduce flickering.
This is close, but you'll need to massage the positioning.
function createPopup() {
var container = document.createElement('div');
container.id = 'popup';
container.style.width = '500px';
container.style.height = '700px';
container.style.display = 'none';
container.style.position = 'absolute';
container.style.borderRadius = '2px';
container.style.border = '1px solid #242729';
container.style.backgroundColor = '#535a60';
container.style.color = '#e4e6e8';
container.style.zIndex = '9999999';
container.addEventListener('xmouseenter', function() {
window.inside_popup = true;
//console.log('window.inside_popup = true;');
});
container.addEventListener('xmouseleave', function() {
window.inside_popup = false;
//console.log('window.inside_popup = false;');
});
container.appendChild(document.createTextNode('This is a test'));
(document.body || document.documentElement).appendChild(container);
}
window.inside_popup = false;
createPopup();
function showPopup(e) {
var popup = document.getElementById('popup');
if (popup.style.display == 'none') {
popup.style.display = 'block';
}
}
function hidePopup(/*e*/) {
console.log('hiding')
popup.style.display = 'none';
window.inside_popup = false;
}
var bodyRect = document.body.getBoundingClientRect()
function updatePopup(e) {
var elemRect = e.target.getBoundingClientRect(),
offsetY = elemRect.bottom - bodyRect.top,
offsetX = elemRect.left - bodyRect.left;
popup.style.left = (e.clientX + offsetX) + 'px';
popup.style.top = offsetY + 'px';
}
var targ = document.querySelector('ul li')
targ.addEventListener('mouseenter', showPopup);
targ.addEventListener('mouseleave', hidePopup);
targ.addEventListener('mousemove', updatePopup)
Fiddle
Here's a pure CSS solution (I only use JS to create the popup elements)
window.addEventListener("load", function () {
var els = document.querySelectorAll("li");
els.forEach(el => {
var popup = document.createElement("div");
popup.innerHTML = el.getAttribute("popup");
popup.className = "popup";
el.appendChild(popup);
});
});
*[popup]:hover > .popup {
border: 1px solid #fff;
padding: 0.5em;
width: 400px;
height: auto
}
.popup {
overflow: hidden;
box-sizing: border-box;
background-color: black;
color: #ccc;
border-radius: 3px;
position: absolute;
height: 0px;
}
li {
margin: 2em 0
}
<ul>
<li popup="Some more info about this product">Move the mouse here</li>
<li popup="Some more info about the 2nd product">Some other product</li>
</ul>
The key to this is that the popup is a child of the element that is hovered, thus moving the mouse over the popup still counts as hovering the element.

Simple range /value Slider in JavaScript

I am trying to do a simple Range/Value Slider by using javascript or jQuery, A button in a div.This slider should be done without bootstrapor any other pluginor with inbuild functions
My question is how to move the slider button within the div element and what mouse events are needed to do this?
Note:This is not a slideshow slider or image slider
Take a look at this simple slider implementation. Feel free to use and modify the way you prefer:
document.addEventListener('DOMContentLoaded', function() {
var sliders = document.querySelectorAll('.my-slider');
[].forEach.call(sliders, function(el, i) {
var btn = el.firstElementChild,
span = el.nextElementSibling.querySelector('span'),
isMoving = false;
var move = function(e) {
if (isMoving) {
var min = 0,
max = el.offsetWidth - btn.offsetWidth,
mousePos = (e.pageX - el.offsetLeft - (btn.offsetWidth / 2)),
position = (mousePos > max ? max : mousePos < min ? min : mousePos),
value = Math.floor((position / max) * 100);
btn.style.marginLeft = position + 'px';
btn.value = value;
span.textContent = value;
}
};
el.addEventListener('mousedown', function(e) {
isMoving = true;
move(e);
});
document.addEventListener('mouseup', function(e) {
isMoving = false;
});
document.addEventListener('mousemove', function(e) {
move(e);
});
});
});
.my-slider {
width: 250px;
border: 1px solid #999;
border-radius: 3px;
background-color: #ccc;
height: 10px;
line-height: 10px;
}
.my-slider__button {
border: 1px solid #333;
border-radius: 3px;
margin-top: -4px;
width: 18px;
height: 18px;
background-color: #eee;
display: block;
}
div {
margin-top: 6px;
}
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
<div class="my-slider">
<button class="my-slider__button"></button>
</div>
<div>
<strong>Current value: </strong><span></span>
</div>
You use drag and drop events, with a property setting that is restricted to the div it is within. Check out this link Drag Drop Reference Guide, and you will see everything you need. When you use draggable and dropable, you can restrict the movement to horizontal, and also set the element that it is bound to. This will allow you to only move left to right, and restrict vertical movement, and keep in the boundaries of the div. The same features bootstrap uses to get it done.
Here is a basic example showing some of the stuff mentioned:
$('. draggable').draggable({
axis: 'y',
handle: '.top'
drag: function( event, ui ) {
var distance = ui.originalPosition.top - ui.position.top;
// if dragged towards top
if (distance > 0) {
//then set it to its initial state
$('.draggable').css({top: ui.originalPosition.top + 'px'});
}
}
});
try this :
$('img').mouseenter(function(){ //or you can use hover()
// Set the effect type
var effect = 'slide';
// Set the options for the effect type chosen
var options = { direction: "right" };
// Set the duration (default: 400 milliseconds)
var duration = 1000;
$(this).toggle(effect, options, duration);
});

Categories