Get ID of preceding image on click event - javascript

I have this HTML code
<div> <img src="download1.jpeg" image-id="9a8ae555af5f"></div>
<div><h1>test</h1></div>
When a user clicks on the "test" link, i would like to navigate through the tree and fetch the "image-id" attribute of the image preceding the link
I have tried this but imageID returns undefined
function trackClick(event)
{
let imageId = this.$('a').prev('img').attr('image-id');
console.log("imageId", imageId);
}
document.addEventListener('click', trackClick, true);
Any ideas on how i can make this work using js or css selectors?
thanks

This is jquery solution with prev() and parent() function:
$('#test').on('click', function() {
alert($(this).parent().parent().prev('div').find('img').attr('image-id'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<img src="download1.jpeg" image-id="9a8ae555af5f">
</div>
<div>
<h1>
<a href ="#" id = 'test'>test</a>
</h1>
</div>

Using Vanilla JS, step by step:
function trackClick(event)
{
let targetElement = event.target || event.srcElement;
let closestDiv = targetElement.closest('div');
let previousDiv = closestDiv.previousElementSibling;
let insideImage = previousDiv.getElementsByTagName('img');
// or
// let insideImage = previousDiv.children;
console.log(insideImage[0].getAttribute('src'));
}
document.addEventListener('click', trackClick, true);

Related

how to add click only on button

I am using jquery to bind a click on a button. In this var testId i am getting the id of the button and var showmoreId is getting the id of a div but the problem is onclick binds with the li so when i click anywhere in li onclick is working but i want it to work on button click and i also want the id of the div on click but do not want li to work on click so what can i do to fix it.
async function userData(userdata) {
let newValue = "";
userdata.forEach(max=> {
let add = `<div class="rb-container">
<ul class="rb">
<li>
<div>
<p>${max.name}</p>
<div>
<p>${max.email}</p>
<button id="showMoreLess_${max.id}" data-order-id="${max.id}">View More</button>
</div>
<div id="showme_${max.id}" class="showBlock" style="display:none";>
<div>
<div>
<p>Quantity:</p>
<p>${max.volume}</p>
</div>
<div>
<p>${max.group_email}</p>
<p>Group_Email</p>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>`
newValue += add ;
let container = document.querySelector('.user-details');
container.innerHTML = newValue;
}
$(document).ready(function() {
$('.rb-container li').unbind('click');
$('.rb-container li').on('click', function () {
var testId = $(this).find('button').attr('id');
var showmoreId = ($(this).find('div > div').next().attr('id'));
viewFullDetails(testId, showmoreId);
});
The .on() function supports an optional selector to handle events on certain child elements.
$('.rb-container li').on('click', 'button', function() {
var testId = $(this).attr('id');
var showmoreId = $(this).closest('li').find('div > div').next().attr('id');
viewFullDetails(testId, showmoreId);
});
Note that I just added the selector 'button' but of course you can use any selector, e.g. #id. I then found the closest li to go from there to get the showmoreId.
Please also consider to use .off() instead of .unbind() as the latter has been deprecated.

how to toggle <div> tags hidden and visible with <span> and JS?

I am building a site with a search bar, but there is too much search content and I need a way for people to toggle it being hidden
<div class="search">
<ul>Bash Shell Emulator</ul>
<ul>How to use bash shell </ul>
much more to this. But how can I toggle it being hidden and it being shown with JS and <span>?
Thank you very much,
Ring Games
Hi you can use toggle to add and remove a class, and with the class you can hide the elements inside the search, this is an example:
const searchElement = document.getElementById("search");
const toggleElement = document.getElementById("toggle-visibility");
toggleElement.addEventListener("click", toggleSearchVisibility);
function toggleSearchVisibility() {
searchElement.classList.toggle("hide-element")
}
.hide-element{
display: none;
}
<div id="search">
<ul>Bash Shell Emulator</ul>
<ul>How to use bash shell </ul>
</div>
<span id="toggle-visibility">Click me!</span>
I would strongly suggest you use the JQuery library. Its super easy, all you need to do as add the following script to your <head> tag:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
Then it would be simple as:
$("#clickedElementThatWillHide").click(function(){
$("span").hide();
});
For more examples checkout W3Schools
Here is Vanilla Javascript without using big library
<p>
<a class="toggle" href="#example">Toggle Div</a>
</p>
<div id="example">
<ul>Bash Shell Emulator</ul>
<ul>How to use bash shell </ul>
</div>
<script>
var show = function (elem) {
elem.style.display = 'block';
};
var hide = function (elem) {
elem.style.display = 'none';
};
var toggle = function (elem) {
// If the element is visible, hide it
if (window.getComputedStyle(elem).display === 'block') {
hide(elem);
return;
}
// Otherwise, show it
show(elem);
};
// Listen for click events
document.addEventListener('click', function (event) {
// Make sure clicked element is our toggle
if (!event.target.classList.contains('toggle')) return;
// Prevent default link behavior
event.preventDefault();
// Get the content
var content = document.querySelector(event.target.hash);
if (!content) return;
// Toggle the content
toggle(content);
}, false);
</script>

Finding the value of a class within a list

I have
<ul id="list">
<li data-markerid="0" class="">
<div class="list-label">A</div>
<div class="list-details">
<div class="list-content">
<div class="loc-id">2</div>
<div class="loc-addr">England</div>
<div class="loc-dist">2 miles</div>
<div class="loc-addr2">Test</div>
<div class="loc-addr2">Bristol</div>
</div>
</div>
</li>
<li data-markerid="1" class="">
<div class="list-label">A</div>
<div class="list-details">
<div class="list-content">
<div class="loc-id">3</div>
<div class="loc-addr">England</div>
<div class="loc-dist">60 miles</div>
<div class="loc-addr2">Test</div>
<div class="loc-addr2">London</div>
</div>
</div>
</li>
</ul>
I'm wanting to extract the value of this using JQuery.
I tried:
var targetID = $(this).find('.loc-id').text();
But this gets me values of both loc-id's. I want just the one that I'm selecting (clicking).
For full context, please look here: Parsing data using JQuery
$('#list').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
// Since array of objects isn't indexed, need to loop to find the correct one
var foundObject = null;
for (var key in parsedArray) {
if (parsedArray.hasOwnProperty(key) && parsedArray[key].id == targetID) {
foundObject = parsedArray[key];
break;
}
}
// If the object is found, extract the image and set!
if (!foundObject)
return;
var imageSrc = foundObject.LocationPhoto; // From the object
$('#location-image').attr('src', imageSrc); // Set the new source
});
Thanks
In your click handler, this references the <ul> element which has multiple <li> children.
Change the click handler to act as a delegate instead:
$('#list').on('click', 'li', function () {
Now, inside the click handler, this references an <li> element so the search should only yield a single value.
For var targetID = $(this).find('.loc-id').text(); to work, you must be clicking an element that is an ascendant of only one .loc-id. For example:
$('.list-details').on('click',function(){
var targetID = $(this).find('.loc-id').text();
});
You need to change selector. In your event handler. $(this) referes to ul which has multiple loc-id thus when you are using text() its concatenating text.
Use
$('#list li').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
alert('targetID: ' + targetID)
});
instead of
// When we select the item
$('#list').click(function () {
//Change the src of img
var targetID = $(this).find('.loc-id').text(); // Get the ID
DEMO
You could use event.target in case you are delegating on #list:
Demo: http://jsfiddle.net/abhitalks/CxcU8/
$("#list").on("click", function(e) {
var $t = $(e.target);
if ($t.hasClass('loc-id')) {
alert($t.text());
}
});

jQuery: add multiple data attributes with each click function

I have a click function setup whereby when you click on the .click div, it takes the data-hook attribute, and add it as a data-filter attribute to the .button div, this works fine, but after each click it is replacing the data-filter attribute with the new one, ideally I want to add a new value to the attribute with each click, separating each value with a comma.
Here's a jsFiddle demo: http://jsfiddle.net/neal_fletcher/pSZ2G/
HTML
<div class="button">THIS</div>
<div class="click" data-hook="one">CLICK</div>
<div class="click" data-hook="two">CLICK</div>
<div class="click" data-hook="three">CLICK</div>
<div class="click" data-hook="four">CLICK</div>
<div class="click" data-hook="five">CLICK</div>
jQuery:
$(".click").click(function () {
var thing = $(this).attr("data-hook");
$('.button').attr('data-filter', thing);
});
If this is at all possible? Any suggestions would be greatly appreciated!
You can store the previous value and can concatinate with new clicked value, something like.
$(".click").click(function () {
var thing = $(this).attr("data-hook");
var earData = $('.button').attr('data-filter');
if(typeof earData != 'undefined'){
$('.button').attr('data-filter', earData + ","+thing);
}else{
$('.button').attr('data-filter', thing);
}
});
DEMO
$(".click").click(function () {
var thing = $(this).attr("data-hook");
var prevValue = $('.button').attr('data-filter');
if(prevValue){
$('.button').attr('data-filter', prevValue +','+thing)
}
else{
$('.button').attr('data-filter', thing)
}
});
$(".click").click(function () {
var thing = $(this).attr("data-hook")||'';
var df = $('.button').attr('data-filter')||'';
$('.button').attr('data-filter', df+','+thing)
});
on a side note.. I hope you don't have any other elements with a .button class in it.. if you're looking to update a single target, you should reference by an id attrib instead.

find the img id and src and adding to the array

Heres my html code:
<div id="cmdt_1_29d" class="dt_state2" onclick="sel_test(this.id)">
<img id="cmdt_1_29i" onclick="dropit('cmdt_1_29');"
src="http://hitechpackaging.zes.zeald.com/interchange-5/en_US/ico_minus.png">
<span class="dt_link">
CARTON & BOARD
</span>
</div>
<div id="cmdt_2_31d" class="dt_istate1" onclick="sel_test(this.id)">
<img src="/site/hitechpackaging/images/items/test.jpb ">
CORRUGATED & CORNER BOARD
</div>
The dropit function modifies my img src which I dont want to, unfortunately I cant modify,
Can I somehow read the data into array before it is being modified and that I can add the data back to the image.
To remove the click handler:
var i = document.getElementById('cmd1_1_29i');
i.onclick = null;
Or, if you want to still call the original click handler:
var i = document.getElementById('cmd1_1_29i');
_onclick = i.onclick;
i.onclick = function(e) {
// do what you want here
_onclick && _onclick.apply(this, [e]);
}
​

Categories