Get Child Attribute using JQUERY - javascript

I am creating a link gallery.
HTML:
<div class="link">
<header>Test Header</header>
Click Here
</div>
I want to go to the A element's URL when clicking anywhere in the div.
Javascript with JQUERY 3.2.1:
$(function() {
$("div.link").click(function() {
$url = $this.children("a").attr("href");
alert($url);
});
});
It doesn't alert the URL
I have also tried:
$(function() {
$("div.link").click(function() {
$url = $this.find("a:first-child").attr("href");
alert($url);
});
});
It returns a collection instead of a single element so I tried the following:
$function() {
$("div.link").click(function() {
$url = $this.find("a");
alert($url[0].attr("href"));
});
});
Neither approach is working. I have confirmed the click selector is functioning by testing it with a simple alert("hello");
EDIT: I was using $this instead of $(this).

I want to goto the A element's URL when clicking anywhere in the div.
Based on the code you have shared, $this seems to be undefined
If you just want to fetch the href property of the child anchor tag, then simply
$("div.link").click(function() {
var href = $(this).find("a").attr( "href" ); //attr will fetch the attribute of first element in the result of find
});
If you want to click on the child anchor tag, then try using one of the following ways
$("div.link").click(function() {
$(this).find("a").first().click();
});
or
$("div.link").click(function() {
$(this).find("a").click();
});
or
$("div.link").click(function() {
$(this).find("a").trigger( "click" );
});
or if you just want to go the URL
$("div.link").click(function() {
window.location.href = $(this).find("a").attr( "href" );
});

If you want to get the href attribute when clicking on the div element, you can consider using the selector $(".nameOfDivClass"). On the element selected you will bind a function that will get your href.
$(".link").on("click", function(){
console.log($(this).children("a").attr("href"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
<header>Test Header</header>
Click Here
</div>

If you check your browser's console, you'll have an error saying $this is not defined. It should be $(this), in order to turn this (the raw HTML element clicked on) into a jQuery object on which you can the run jQuery methods such as .find() and .attr().
Additionally, this version will actually cause the navigation action rather than just alerting the URL:
$("div.link").click(function() {
$(this).find("a").click();
});

Related

Code not dynamically updating itself

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
$.getJSON('http://anyorigin.com/get?url=microsoftwebpro.com&callback=?',
function(data){
$('#output').html(data.contents);
$('a').each(function() {
$(this).attr('href', 'http://anyorigin.com/get?url='+$(this).attr('href')+'&callback=?');
});
});
$('a').click(function() {
$.getJSON($(this).attr('href'), function(data) {
$('#output').html(data.contents);
});
});
But I can't seem to figure out why it isn't loading in the right order.
So for example, I want it to load the contents from another domain, then add an add filter href to all the links in the "output" div and only that div(not working)
And then if I click a link it updates the "output" div instead of actually navigating to the link.
One solution is to bypass changing the <a> elements and just capture the clicks. Since you're dealing with dynamically created elements, it will probably be easier to use Event Delegation:
function AnyOriginURL(url) {
return 'http://anyorigin.com/get?url='+url+'&callback=?';
}
function Navigate(url) {
$.getJSON(AnyOriginURL(url), function(data){
$('#output').html(data.contents);
});
}
// When clicking any <a> inside the #output...
$("#output").on("click", "a", function(e) {
// Prevent click from triggering navigation
e.preventDefault();
// And Navigate there using our method
Navigate($(this).attr("href"));
});
// Onload, start at this base page
$(function() {
Navigate("microsoftwebpro.com");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Take heed: When using this example, the website is very slow to load

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

use selectors in variable jquery

i have to made functionality like this on click of a link it will show the product details in a popup like box
this is using a big jquery code i didn't understand
and here is my jsfiddle
i am trying to give some links same class with different #tags to show the div
and i want that when i click on link it resolves the href value of the same and show the corresponding result but it didnt works
can somebody suggest the right way
here is my JS
$(".show").click(function() {
var link = $('this').attr('href');
$(link).show();
});
and html
a
b
c
i want to show #popup on anchor click
full code on fiddle and i want this functionality
You should call $(this), not $('this')
$(this) wraps the object referred to by this inside a jQuery object,
$('this') will traverse all of your document looking for html nodes tagged this (much like $('div') will look for html nodes tagged div); since there isn't any, it will select an empty list of nodes.
Working fiddle : http://jsfiddle.net/Hg4zp/3/
( there also was a typo, calling .hide(") instead of .hide() )
Try this way:
$(".show").click(function (e) { //<-----pass the event here
e.preventDefault(); //<--------------stop the default behavior of the link
var link = $(this).attr('href'); //<-remove the quotes $(this)
$(link).show();
});
$(".close").click(function () {
$(this).closest("div.popupbox").hide(); //<----use .hide(); not .hide(");
});
You should use preventDefault() in these cases to stop the jump which take place when a link get clicked.

How to change a hidden value and the text of the

I am currently attempting to make a dropdown menu where selecting one of the links from the menu will change the hidden value as well as the text of the hyperlink. This is based upon Twitter's Bootstrap dropdown, and uses jQuery:
<div id="periodChooser" class="btn-group">
<input type="hidden" value="1" name="dtype" id="dtype1"></input>
<a data-toggle="dropdown" href="javascript:;">Weekend</a>
<ul class="dropdown-menu">
<li>Weekend</li>
<li>Week</li>
<li>Midweek</li>
</ul>
</div>
The script that I have attempted to write is as follows:
<script>
jQuery(function($){
$('#periodChooser').each(function() {
$('.dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
});
});
</script>
Unfortunately, whilst it doesn't return any specific error, the code does not work. Any suggestions?
Bind event out side each
<script>
$('#periodChooser .dropdown-menu a').click(function() {
$('.btn-group').find('input[type=hidden]').val($(this)
.data('value')).change();
$('.btn-group').find('.btn:eq(0)').text($(this).text());
});
</script>
I think that this can be optimized and made more re-usable.
First of all, you are using jQuery selectors like $('.btn-group') very ineffectively.
Secondly it will break, if you will use more than one "widget", because the context is whole document and it will find all elements with that class .btn-group.
Thirdly it would be more effective to use single event handler that is being binded to the parent <ul> element instead of each <a> element. It's called "event delegation". http://api.jquery.com/delegate/
<script>
$('#periodChooser').each(function() {
var $input = $('input', this),
$select = $('>a', this);
$('ul', this).on('click', 'a', function() {
var $this = $(this);
$input.val($this.data('value')).change();
$select.html($this.html());
});
});
</script>
I made this code available in JSBin: http://jsbin.com/welcome/38724/edit
What I did here?
<script>
$('#periodChooser').each(function() {
// Find and store input and "select" element only once.
var $input = $('input', this),
$select = $('>a', this); // This finds only direct child element <a>
// Find the <ul> element inside the #periodChooser
// Bind a click event that will "bubble up" from <a> elements that are children of it
$('ul', this).on('click', 'a', function() {
// Wrap a jQuery around the <a> element
var $this = $(this);
// Set the input value and execute "change" event(s)
$input.val($this.data('value')).change();
// Change the "select" title. Doesn't matter if you use html() or text() - choose yourself!
$select.html($this.html());
});
});
</script>
Now, you can use this to make multiple widgets inside single page! :)
<script>
$('.btn-group').each( /* Well, you know, the function goes here... */ );
</script>
Of course, threre are many other things that has to be done here, like opening and closing the "option list", scrolling and probably many other things...

How to get the id of an element ON PAGE LOAD using jQuery

I simply know how to get the id of a clicked element it's like this:
$("button").click(function(){
console.log($(this).attr("id"));
}
but what can I do for getting the id on web page load? Look at this..
$("button").ready(function(){
console.log($(this).attr("id"));
}
it returns the whole document object and this one ..
$("button").load(function(){
console.log($(this).attr("id"));
}
simply does nothing.
I want to dynamically change the styles of all buttons on load.
The main project is more complicated, and I don't want to use js core to do it, I want the simplicity of jQuery selector, but equivalent js approaches are appreciated.
i want to dynamically change the styles of all buttons on load.
If that is the case you can simply apply the css to the button selector on load, without needing to get the id of each button.
$(function() {
$("button").css("background-color", "#C00");
});
Or better yet, put the css styling into a class and just apply a class to all the buttons:
$(function() {
$("button").addClass("red-bg");
});
If you did want to get the id of each button on load, you'd need to use an array to cater for the fact there may be more than one button:
var buttonIds = $("button").map(function() {
return this.id;
}).get();
However, this is a rather pointless method as you can just use each() to iterate over the button selector anyway to get access to each indiviual button element.
you can get the all button elements in jquery and then loop on each button element to change their style -:
$(function()
{
var allButtons = $('button');
$.each(allButtons,function(index,element)
{
$(element).css('width','100px');
});
});
I think you're looking for this:
$(document).ready(function () {
$(":button").each(function () {
console.log($(this).attr("id"));
})
});

Categories

Resources