Getting data-position value from parent div on link click - javascript

I am trying to get the data-position value using jquery on link click. Here is my code
<div class="dfd-article-tile-wrapper tile-position-6">
<div id="f_54ae4352d493b83429617a69" data-position="5" class="dfd-item tile">
<a class="dfd-item-wrap cxense" target="_blank" href="#">
<div class="imageholder">
<img src="#" alt="Depresjon - en oversikt " style="background-image: url(image.png);">
<div class="shader" style="">
<h2 class="dfd-tile-header">Hello World </h2>
<span class="source">xyz.com</span>
</div>
</div>
</a>
</div>
</div>
What I have tried so far to code this jquery code but it is not working;
<script type="text/javascript">
jQuery(document).ready(function($) {
$(".dfd-item-wrap").click(function(event) {
var text = $(this).parents(".dfd-item").find('data-position').value
alert(text);
});
});
</script>
This is the jsfiddle link
http://jsfiddle.net/nt7243s6/
Need help and guidance. Thank you

You need to use .data() instead of .find() to get data attribute value. also use .closest(.dfd-item) or .parent() instead of .parents():
var text = $(this).closest(".dfd-item").data('position');
Complete Code:
$(".dfd-item-wrap").click(function(event) {
event.preventDefault();
var text = $(this).closest(".dfd-item").data('position');
alert(text);
});
Working Demo

The way you should access your data attributes is simply by data('position');
http://jsfiddle.net/nt7243s6/2/

Related

How to target child div by Javascript?

I want to apply JavaScript on sticky header in my site. For this I want to target a div inside sticky div by JavaScript. Please let me know how to target a dive that is inside some other divs by JavaScript.
var yourHTML = '<div class="mynewdiv">Test</div>';
document.getElementsByClassName('at-sticky' 'custom-logo-link')
[0].innerHTML = yourHTML;
<div class="at-sticky">
<div class="container">
<div class="navbar-header">
<a href="#" class="custom-logo-link"
rel="home" itemprop="url">
<img src="#" class="custom-logo">
</a>
</div>
</div>
</div>
You can try with Document​.query​Selector() which allows CSS like selector:
var yourHTML = '<div class="mynewdiv">Test</div>';
document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;
<div class="at-sticky">
<div class="container">
<div class="navbar-header">
<a href="#" class="custom-logo-link"
rel="home" itemprop="url">
<img src="#" class="custom-logo">
</a>
</div>
</div>
</div>
Please use querySelector()
var yourHTML = '<div class="mynewdiv">Test</div>';
document.querySelector('.at-sticky .custom-logo-link').innerHTML = yourHTML;
Simplest solution is using querySelector
Example:
document.querySelector('.at-sticky .container .custom-logo-link').innerHTML = yourHTML
Please put the comma in between the class names:
document.getElementsByClassName('at-sticky', 'custom-logo-link')[0].innerHTML = yourHTML;
Ok 2 points:
Firstly when using innerHTML you are inserting text into your element, not the full tag as you have done.
Secondly you only need pass in to ‘document.getElementsByClassnames’ the class name that you are targeting. Dont worry about the parent div, that should work fine as is.
I would have posted a comment but I don’t have enough reputation yet;)
You can use children() function for this.
$('.at-sticky').children();
You can use querySelector for this.
Let's say you have the following HTML structure
<div class="parentDiv">
</div>
Then you can do this in JavaScript
let parentDiv = document.querySelector('.parentDiv')
let childLink = parentDiv.querySelector('a')
console.log(childLink)

Jquery open this link not the others

So, I have a series of divs and inside each div there is a link.
What I want to accomplish is to open in another window or tab the .pdf file if the link ends in.pdf if not do nothing or something else to decide later.
The problem I'm having is that when you click on the link it will open the same document as many times as you have .pdfs on the page.
I tried replicating the problem in this fiddle:
https://jsfiddle.net/x9fo6cgk/
But it isn't working. The code works on my side.
Here is the code:
$('.somelink').click(function(eventObject) {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
eventObject.preventDefault();
elem.attr('target', '_blank');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="linkholder">
<a class="somelink" href="https://bitcoin.org/bitcoin.pdf">pdf 1</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.pdf995.com/samples/pdf.pdf">pdf 2</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.bing.com">.com</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.google.org">.org</a>
</div>
Thanks in advance!
You should just change the targets on page load if they are PDFs.
$('.somelink').each(function() {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
elem.attr('target', '_blank');
}
});
JSFiddle: https://jsfiddle.net/x9fo6cgk/3/
Results in this HTML:
<div class="linkholder">
<a class="somelink" href="https://bitcoin.org/bitcoin.pdf" target="_blank">pdf 1</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.pdf995.com/samples/pdf.pdf" target="_blank">pdf 2</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.bing.com">.com</a>
</div>
<div class="linkholder">
<a class="somelink" href="http://www.google.org">.org</a>
</div>
Note: Your JSFiddle did not have jQuery selected so nothing ran.
You can do like this:
$('.somelink').click(function(eventObject) {
var elem = $(this);
if (elem.attr("href").match(/\.pdf$/i)) {
eventObject.preventDefault();
window.open(elem.attr('href'));
}
});
Look here: https://jsfiddle.net/x9fo6cgk/6/
For some reason the behavior of this script:
https://learn.jquery.com/events/event-basics/#preventdefault
under Magnolia CMS acts a bit weird.
So this code was used instead:
$(".linkholder a[href$='pdf']").attr('target','_blank').addClass('pdf');
$(".linkholder a:not(a[href$='pdf'])").addClass('generic');
Here is a the fiddle:
https://jsfiddle.net/x9fo6cgk/13/
Thanks everyone!

how to get the href of a link when i press another href

i want to get the attr href of an above link beside the one i press wich is the last link from productinfo div class. I tryed with closest but it gets me the same link i press and i want the above one. The link i want to store in produs_href is the link from first href under productinfo class. Here is my code:
<div class="col-sm-4 produse"><!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<img src="/images/produse/'.$recomand['ID_Produs'].'/'.$recomand['Poza'].'" alt="" />
<h2 style="text-decoration: line-through;">'.$recomand['Pret'].' lei </h2><h2>'.$recomand['Pret_Nou'].' lei </h2>
<p>'.$recomand['Nume_Prod'].' '.$recomand['Gramaj'].' '.$tip.'</p>
<i class="fa fa-shopping-cart"></i>Adaugă în coș
</div>
</div>
</div>
</div>
jquery
<script>
$(".cos").click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('a').attr('href');
$.getJSON(href, function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#test").append('<li>' + val.nume + '</li>')
$("#cnt").append('' + val.cnt +'')
});
});
$(\'#detalii_prod\').modal('show');
alert(produs_href);
});
</script>
Use prev. This method gets the immediately preceding sibling.
$(this).prev().attr('href');
EDIT
From your comments, the code that would do the trick is
$(this).closest('.productinfo').find('a:first').attr('href');
You can use the .prev
var link = $(this).prev().attr('href');
and now you can use link.
you can use like this
$(this).prev("a").attr("href");
and more help:
Get the href value of a previous HTML anchoer, <a>, using jQuery
$(".cos").click(function(e){
e.preventDefault();
var text = $(this).parent().find('a:first').attr('href');
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 produse">
<!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center"> <img src="img/Penguins.jpg" height="50" width="50" alt="" />
<h2 style="text-decoration: line-through;">Hello there</h2>
<h2>Anto</h2>
<a href="link produs">
<p>Angeline</p>
</a> <i class="fa fa-shopping-cart"></i>Test </div>
</div>
</div>
</div>
try this
$(this).parent().find('a:first').attr('href');
Try with .eq() method.
$(this).parent().find('a').eq(0).attr('href');
Hope this helps you...

how to catch up a html element with same class which is under different parent using jQuery?

My markup is as follows:
<li class="item">
<div class="quickview-btn" data-pid="147" style="opacity: 0;">Quick View</div>
<a class="product-image" title="xyz" href="http://def.com/xyz"><img alt="xyz" src="http://def.com/asdf">xyz</a>
<h2 class="product-name"><a title="xyz" href="http://def.com/xyz">22" Syncmaster LCD Monitor</a></h2>
<div class="price-box">something</div>
</li>
<li class="item">
<div class="quickview-btn" data-pid="163" style="opacity: 0;">Quick View</div>
<a class="product-image" title="abc" href="http://def.com/abc"><img alt="abc" src="http://def.com/ghjk">abc</a>
<h2 class="product-name"><a title="abc" href="http://def.com/abc">Another Product</a></h2>
<div class="price-box">something</div>
</li>
I want to get the data-pid value of the second quickview-btn div on clicking the first quickview-btn div.
I used the .parent(), .next(), and .closest() methods in jQuery, but I'm not able to get it.
I tried:
$(this).parent('.item').next('.item').next('.quickview-btn').data('pid');
$(this).parent('.item').next('.item').child('.quickview-btn').data('pid');
$(this).parent('.item').next('.item').closest('.quickview-btn').data('pid');
but none of them worked for me.
$(this).parent('.item').next('.item').hide(); //this works
$('.quickview-btn').on('click',function(){
var pid = $(this).closest('.item').next('.item').find('.quickview-btn').data('pid');
})
Demo ----> http://jsfiddle.net/qSe6t/4/
Try
$('li.item').closest('.item').find('.quickview-btn').data('pid');
For direct access on load you can use this way. This is not recommended but one of the ways.
$("li:nth-child(2) .quickview-btn").data('pid');
Try the following:
$('.quickview-btn').on('click',function(){
var pid = $(this).parent().next().find('.quickview-btn').attr('data-pid');
});
You could simplify your code in addition to using the proper selectors, as follows:
$('li:first-child').find('.quickview-btn').on('click', function () {
var nextData = $(this).parent().next().children('.quickview-btn').data('pid');
console.log(nextData);
});
Demo

Replacing dhtml element without using innerHTML

This seems like it should be easy. I have a html snippet that I wish to locate and modify in place via javascript. But not just the innerHTML; I want to replace the entire element. Example:
<div class="content">
<div class="item">
<img src="images/pic1.jpg" />
<a class="clicker" onclick="javascript:doSomethingUseful(##);">Do ##!</a>
<h3>title</h3>
<p>description</p>
</div>
</div>
After page load, I want to grab the <a class="clicker" ...>Now!</a> and replace it with three instances like:
<div class="content">
<div class="item">
<img src="images/pic1.jpg" />
<a class="clicker" onclick="javascript:doSomethingUseful(1);">Do 1!</a>
<a class="clicker" onclick="javascript:doSomethingUseful(2);">Do 2!</a>
<a class="clicker" onclick="javascript:doSomethingUseful(3);">Do 3!</a>
<h3>title</h3>
<p>description</p>
</div>
</div>
Using prototype.js, I can easily do $$('.clicker') and get an array with the element. I can use .innerHTML and get the 'Do ##!' and change it. But I want, nay, need the entire element to insert it in place. I can go through weird machinations of siblings and parent, and walk back around the nodes to eventually get what I need, and I will do that. It just seems that I am missing something here that would make this easy.
If it is not the only HTML generation you want to run in your page, you may consider a javascript templating engine.
There are several advantages, the main one being a clear cut between the HTML view and the JS logic.
There are plenty of these engines available for every taste.
Here is how it would look with prototype.js and the PURE template engine:
$$('div.content')[0].render([1,2,3], {
'a.clicker':{
'id <-':{
'.':'Do #{id}!',
'#onclick':'javascript:doSomethingUseful(#{id});'
}
}
});
In IE you can set outerHTML. In FF, you can use this:
http://snipplr.com/view/5460/outerhtml-in-firefox/
So the way I would do this is:
Iterate over all the anchors with class clicker that are inside a div with class item which are inside class content
To each one, add a function which will hide that anchor, and then append the 3 anchors you want
So here's what my html chunk looks like:
<div class="content">
<div class="item">
<img src="images/pic1.jpg" />
<a class="clicker" href='#'>Do ##!</a>
<h3>title</h3>
<p>description</p>
</div>
</div>
And I need to include Prototype:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"></script>
And a variable to hold your replacement html, and a dummy function so what we insert works:
var myReplacementHtml = '<a class="clicker" onclick="doSomethingUseful(1);" href="#">Do 1!</a>';
myReplacementHtml += ' <a class="clicker" onclick="doSomethingUseful(2);" href="#">Do 2!</a>';
myReplacementHtml += ' <a class="clicker" onclick="doSomethingUseful(3);" href="#">Do 3!</a>';
function doSomethingUseful(n) {
alert(n);
return false;
}
Then here's my code, you may find it useful to get the backstory on how these work: $$, Element.observe, Element.hide, Element.insert, Event.stop:
<script type="text/javascript">
Event.observe(window, 'load', function(){
$$('.content .item a.clicker').each(function(item){
item.observe('click', function(evt){
item.hide();
Element.insert(item, {after: myReplacementHtml});
});
Event.stop(evt);
});
});
</script>
You can add and append elements.
function doSomethingUseful(val) {
var ele = document.getElementById('myDiv');
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
ni.appendChild(newdiv);
}

Categories

Resources