Detect if hovering over image in div with jQuery - javascript

I have an example:
<div class="class1" id="id_1">
test
</div>
function handler(ev) {
let target = $(ev.target);
let elId = target.attr('id');
if( target.is("div[id^='id_']") ) {
let lastChar = elId.substr(elId.length - 1);
alert('The mouse was over'+ lastChar );
}
}
$("div[id^='id_']").mouseleave(handler);
It works in such a way that if I hovering on an element, then alert is displayed - the problem occurs if I have only a picture in this div - then it does not work. How to make it work even more if I only have a picture like this, e.g. I have:
<div class="class1" id="id_1">
<img src="/img_src">
</div>

Use $(ev.currentTarget) or $(this) to reference the element that matches the selector rather than any target that is a descendant
function handler(ev) {
console.clear();
let $div = $(ev.currentTarget);
let elId = $div.attr('id');
console.log('currentTarget id:', elId)
$div= $(this);
elId =$div.attr('id');
console.log('this id:', elId)
}
$("div[id^='id_']").mouseleave(handler);
.class1{ margin : 1em; border: 1px solid green
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1" id="id_1">
<div class="inner">test 1</div>
</div>
<div class="class1" id="id_2">
<div class="inner">test 2</div>
</div>

Related

Move button when clicked

How do I move the button from the div with id of two to the div with id of one when I click the button?
<div id="one">
</div>
<div id="two">
<button onclick="moveMe"></button>
</div>
function moveMe() {
// ??
}
We can do this using removeChild and appendChild js features. Provided an example below with working code.
const one = document.getElementById("one");
const two = document.getElementById("two");
const allButtons = document.getElementsByTagName("button");
for(let i = 0; i < allButtons.length; i++) {
const btn = allButtons[i];
btn.addEventListener("click", function(e) {
const el = e.currentTarget;
const newParent = el.parentNode.id == "one" ? two : one;
el.parentNode.removeChild(el);
newParent.appendChild(el)
});
}
.section {
height: 100px;
width: 150px;
padding: 4px;
margin: 5px;
float: left;
}
#one {
background: #CCC;
}
#two {
background: #eee;
}
button {
margin: 2px;
padding: 4px;
}
<h3>Toggle button between container on click</h3>
<div>
<div class="section" id="one"></div>
<div class="section" id="two"> <button>Move me 1</button> <button>Move me 2</button></div>
</div>
function moveMe() {
const divTwo = document.getElementById("two")
const divOne = document.getElementById("one")
const newButton = document.createElement("button")
newButton.innerText = "Click me"
divOne.appendChild(newButton)
divTwo.children[1].remove()
}
<div id="one">
<p>
div one
</p>
</div>
<div id="two">
<p>
div two
</p>
<button onclick="moveMe()">Click me</button>
</div>
You can try this:
// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');
// add eventListener
button.addEventListener('click', moveButton);
// move the button
function moveButton() {
firstDiv.append(button);
}
<div id="one">
</div>
<div id="two">
<button id="btn" onclick="moveMe">MoveMe</button>
</div>
function moveMe() {
var divOne = document.querySelector("#one");
var btn = document.querySelector("#btn");
divOne.appendChild(btn);
}
You can use code below to move the element.
There's some changes that I made on your code,
you can use version 1 or version 2
the changes on first version is i add "id" attribute on the element so we don't resort to use the tag only as selector, of course you can also use #two>button to make it more precise
the changes on second version is i add a parameter to your function this time it will handle the current element using "this" keyword when calling the function
function moveMe(){
// one.appendChild(document.querySelector("button"));
one.appendChild(move);
}
function moveMeV2(element){
one.appendChild(element);
}
<div id="one">
<span>one</span>
</div>
<div id="two">
<span>two</span>
<button id="move" onclick="moveMe()">Move Me</button>
<button onclick="moveMeV2(this)">Move Me V2</button>
</div>

How do I count divs clicked using an event listener in javascript

I'm trying the count the total number of divs clicked and exactly which ones were clicked. I'm using an event listener because the onclick is already used. Let me clarify a bit more, first, here's my code:
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
.selected {
background: white;
}
var numClicked = document.querySelectorAll('.wrapper');
numClicked.forEach(numClicked =>
numClicked.addEventListener('click', clickedDivs)
)
function clickedDivs () {
i = 0;
numClicked.forEach(numClicked =>
i++
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + i;
}
What I'm trying to do with my javascript is count how many divs are selected. I'm also trying to tell exactly where ones were clicked. Let's say 1 and 2 were clicked, how do I find those were clicked and total number of divs clicked using js?
What you are doing wrong here is:
You are initialising i within the onClick event fn. which will always reset the value to 0 when ever the div will be clicked.
you are not storing anywhere which div is clicked
You are adding you'r listener on wrapper instead of .square (if you are not trying to get the value of clicked wrappers instead of clicked square)
So you can modify you'r javascript like this
<style>
.square{width: 100px; height: 100px; background: grey;}
.selected {
background: white;
}
</style>
<div class="wrapper">
<div class="square" onclick="classList.toggle('selected')">1</div>
<div class="square" onclick="classList.toggle('selected')">2</div>
<div class="square" onclick="classList.toggle('selected')">3</div>
</div>
<div id="dis"></div>
<script>
var numClicked = document.querySelectorAll('.square');
numClicked.forEach(numClick => {
numClick.addEventListener('click', clickedDivs)
}
)
var itemsClicked = [] //to store which div is clicked
function clickedDivs (e) {
var value = e.target.innerHTML;
//edit
if(itemsClicked.indexOf(value) != -1) itemsClicked.splice(itemsClicked.indexOf(value), 1)
else
itemsClicked.push(value);
var x = document.getElementById("dis");
x.innerHTML = "Squares selected: " + itemsClicked.join(",");
}
</script>
edit:
added to code to remove data from the list if already exist.
Rather than attach a handler to each div, you can use 1 window event listener. Give each clickable div an id that contains "clickable" so the event listener can filter out divs you aren't tracking. When you first click a tracked div, set its id as a key within a global object and assign 1 as the value; on additional clicks, increase value by 1.
const clicks = {};
window.addEventListener("click", (e)=> {
const id = e.target.id;
if(!id.includes("clickable"))return;
clicks[id]? clicks[id] += 1 : clicks[id] = 1;
console.log(clicks);
},)
<div class="wrapper">
<div id="clickable1" class="square">1</div>
<div id="clickable2" class="square">2</div>
<div id="clickable3" class="square">3</div>
</div>
My solution, I haven't tested it yet, test it and tell me how we adjusted it.
<div class="wrapper">
<div class="square" id="d-1">1</div>
<div class="square" id="d-2">2</div>
<div class="square" id="d-3">3</div>
</div>
<div id="result"></div>
var count = [];
var wrappers = document.querySelectorAll('.wrapper');
wrappers.forEach(square => square.addEventListener('click',() => onClickwrapperSquare(square.id));
function onClickwrapperSquare(id) {
var result = document.getElementById('result');
if(count.indexOf(id) == -1){
count.push(id);
}else{
count = count.slice(count.indexOf(id)+ 1);
}
result.innerHTML = `Squares selected: ${count.length}`;
}
This can be simply achieved by jQuery.
var count;
$(".square").click(function (){
count = count+1;
$("#dis").html(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class=square">1</div>
<div class="square">2</div>
<div class="square">3</div>
</div>
<div id="dis"></div>

How to select element with specific class in a container

<section class="refinementsContainer">
<div class="contentfilters">
<div class="refinementContainer refinementmicro" data-dimension="micro"></div>
<div class="refinementContainer refinementcolor" data-dimension="color"></div>
<div class="rightContainer">
<div class="refinementContainer sort"></div>
<div class="refinementContainer refinementSeason"></div>
</div>
</div>
</section>
I have this code. I need to append one class at only one div into the div with class contentfilters. I develop this code but it doesn't work:
$buttonOpenFilter.on(clickEvent, function(e) {
e.stopPropagation();
e.preventDefault();
var $this = $(this).parent();
var classOpen = 'open';
if ($this.hasClass(classOpen)) {
$this.removeClass(classOpen).css('max-height', 30);
} else {
$this.siblings().removeClass(classOpen).css('max-height', 30);
$this.addClass(classOpen).css('max-height', $this.find('ul').height() + 105);
}
});
$('.contentfilters')
https://api.jquery.com/category/selectors/ here you will find everything about selectors.

How to avoid the particular class from applying css

My HTML
<body>
<div id="finalparent">
<!--many parent divs here-->
<div id="1stparent">
<div id="txt_blog_editor" class="box" style="width: 1097px;">
<div class="abc anotherclass">
</div>
</div>
</div>
</div>
<div class="abc"></div>
</body>
My Script
$('html').on('mouseover','.fr-bttn .fa-picture-o', function () {
var pos = $(this).offset();
console.log(pos.left+"||"+pos.top);
var left_pos=(pos.left-15)+"px";
var top_pos=(pos.top+35)+"px";
$(".abc").css({position: "absolute", top: top_pos, left: left_pos });
$(".abc").show();
$(".popup").show();
});
});
I want to apply the left and top to abc class which is without parent and not to the class which is under id="txt_blog_editor"
According to this answer here is a working snippet:
jQuery.expr[':'].noparents = function(a,i,m){
return jQuery(a).parents(m[3]).length < 1;
};
var elts = $(".abc").filter(":noparents(#txt_blog_editor)");
elts.css({ "background-color": "green" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="finalparent">
<!--many parent divs here-->
<div id="1stparent">
<div id="txt_blog_editor" class="box" style="width: 1097px;">
<div class="abc anotherclass">
ABC With Parent
</div>
</div>
</div>
</div>
<div class="abc">ABC WITHOUT Parent</div>
Basically, you create a new jQuery expression :noparents which returns elements not having selector given parents
You need to check if .abc has a parent #txt_blog_editor http://jsfiddle.net/ugv2pxdw/4/
$('html').on('mouseover','.fr-bttn .fa-picture-o', function () {
var pos = $(this).offset();
console.log(pos.left+"||"+pos.top);
var left_pos=(pos.left-15)+"px";
var top_pos=(pos.top+35)+"px";
$('.abc').each(function(){
if (!$(this).parents('#txt_blog_editor').length) {
$(this).css({position: "absolute",top: top_pos, left: left_pos });
$(this).show();
$(".popup").show();
}
});
});
If abc classes are only direct childs of body, why not using body > .abc as your selector?

auto change div jquery

I am trying to make a div auto hide and show other div like changer. It does not work when I use multi div inside the main div:
<div id="div1">
What actually happens is that it hides all content of the inside div(s)
Is there any way to keep my div(s) for save my style and make an auto changer for my div(s)?
html code
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
<div id="mydiv" style=" left:200; width:100; background-color:#F605C6;">
<div id="main_adv" class="a" style="position:absolute;text-align:left;width:673px;height:256px">
<div id="Layer3" class="a" style="position:absolute;text-align:left;left:176px;top:56px;width:490px;height:171px" title=""></div>
<div id="img_adv" class="a" style="position:absolute;text-align:left;left:4px;top:55px;width:169px;height:172px;" title="">
<img id="ri" class="a" src="thumbs/img1.png" />
</div>
<div id="title_adv" class="a" style="position:absolute;text-align:right;left:4px;top:6px;width:662px;height:40px;" title="">
<div style="position:absolute;text-align:right;right:6px;top:4px;">
<span style="color:#000000;font-family:Arial;font-size:29px;right:5px">some text</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
</div>
</body>
Javascript code
$('html').addClass('js');
$(function() {
var timer = setInterval( showDiv, 400);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$('div','#container')
.stop()
.hide()
.filter( function() { return this.id.match('div' + counter); })
.show('fast');
counter == 16? counter = 0 : counter++;
}
});
I wrote some basic code that changes divs continiously like you asked :
jsfiddle.net/5jhuK/
HTML
<div id='container'>
<div id='div1' class='display' style="background-color: red;">div1</div>
<div id='div2' class='display' style="background-color: green;">div2</div>
<div id='div3' class='display' style="background-color: blue;">div3</div>
</div>
CSS
.display {
display: none;
}
JS (jQuery)
$(document).ready(function () {
var activeDiv = 1;
showDiv(activeDiv); // show first one because all are hidden by default
var timer = setInterval(changeDiv, 2000);
function changeDiv() {
activeDiv++;
if (activeDiv == 4) {
activeDiv = 1;
}
showDiv(activeDiv);
}
function showDiv(num) {
$('div.display').hide(); // hide all
$('#div' + num).fadeIn(); // show active
}
});
It's really not complicated, next time when you ask something try to be concise and remove unnecessary code (like #mydiv)
a few things:
1. html ids are unique, so you can just do something like below:
2. your code was missing a # in the find (e.g. "#div"+counter)
3. you can use the child selector ">" to just target divs one level down
var counter=1;
function showDiv() {
$('#container > div').hide()
$("#div"+counter).show();
counter == 3? counter = 1 : counter++;
}

Categories