Recover href attribute in javascript function? - javascript

I have a problem getting the href attribute of a link. In have the following code in my DOM
$("a").click(function(e) {
e.preventDefault();
myFunction(this);
});
In my linked js file I want to manipule the href attribute, let's say :
function myFunction() {
var hrefValue = $(this).attr("href");
alert(hrefValue );
}
But Is displays 'undefined'.
What am I doing wrong ?
Thanks a lot for your help !

You never accept a parameter in your function!
function myFunction(el) {
var hrefValue = $(el).attr("href");
alert(hrefValue);
}

Try using .call to maintain the context,
myFunction.call(this)

Related

Lazy loading. Why do I see the result of the JavaScript only when it is fully run through? [duplicate]

Why does this function get fired without having clicked on the specified button?
I had a look at a few similar problems but none deal with this code structure (might be obvious reason for this im missing...).
document.getElementById("main_btn").addEventListener("click", hideId("main");
function hideId(data) {
document.getElementById(data).style.display = "none";
console.log("hidden element #"+data);
}
You are directly calling it.
document.getElementById("main_btn").addEventListener("click", hideId("main");
You should do that in a callback.
document.getElementById("main_btn").addEventListener("click", function (){
hideId("main");
});
This code executes your function hideId("main") you should pass just the callback's name:
document.getElementById("main_btn").addEventListener("click", hideId);
function hideId(event) {
var id = event.target.srcElement.id; // get the id of the clicked element
document.getElementById(data).style.display = "none";
console.log("hidden element #"+data);
}
document.getElementById("main_btn").addEventListener("click", hideId.bind(null, "main");

Changing href attribute to generated string from API with jquery

I want to change the href attritube of link on this part of the code
I'm using this code to change the href attribute
$('a').attr('href', function() {
return this.href + update.response;
});
I tried to make a variable in this function
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
var okay = $('.author').html(JSON.stringify(response.quoteAuthor));
}
But I can't seem to access it from outside scope.
Basically I want to link to Wikipedia author page by adding the $('.author') name at the end of link.
Added the update.response to the end of link but I get undefined
CodePen Link
Just update the href at the point you get your response.
eg.
http://codepen.io/anon/pen/rrJYbJ
var a = $('a'),
wiki = a.attr('href');
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
$('.author').html(JSON.stringify(response.quoteAuthor));
a.attr('href',wiki + response.quoteAuthor);
}
Where is response coming from?
did you declare it as a global variable? eg var response;
if so then just place this code:
$('a').attr('href', function() {
return this.href + response; // you dont need update.response just response
});
after wherever you're calling update();
There's some erros in your code:
Where response came from?
You should update link href after receive data from api.
You can try to alter your code like this:
And js:
function update(response) {
$('#response').html(JSON.stringify(response.quoteText));
$('.author').html(JSON.stringify(response.quoteAuthor));
$('a').each( function () {
var newHref = $(this).data('data-base-href')+response.quoteAuthor;
$(this).attr('href',newHref );
});
}

Have the element who call my js function

I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}

How to save "title" attribute of "a" with jQuery?

How can I save the value of the title for a row? These are the values of the title=%s:
<a class="false" title=1106 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1153 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1175 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
...
I've tried countless variations but none of them work. This is what I have now:
<script>
$(document).ready(function() {
console.log("ready");
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = a.title;
var display = "false";
e.preventDefault();
});
$("a.false").click(function() {
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
data: {main_id: "main_id", display: "display"},
success: function(data) {
display_false()
alert("4 - returned");
}
});
});
});
</script>
This is the third question on this topic. I appreciate any help. Thanks.
instead of
var main_id = a.title;
try
var main_id = $(this).attr('title');
because if I'm not wrong, "a" isn't defined
I think what you're trying to do is pass the value of the title attribute along in your AJAX request. If that's the case, the easiest thing to do will be to do it all in one event handler (is there a reason you're binding 2 different handlers to the same event?):
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title;
var display = "false";
e.preventDefault();
$.ajax({
url: "/useradminpage",
data: {main_id: main_id, display: display},
success: function(data) {
display_false();
alert("4 - returned");
}
});
});
Your problem currently is that main_id and display are not in the scope of the second event listener, so will be undefined (and they shouldn't be quoted, otherwise you're just passing in strings). As you're passing in a data object to the ajax function, you don't really need to add the query string to the URL either.
Aside from that, when you assign a value to main_id, you're using a.title. In this case a is undefined, and you will need to use this, which will be a reference to the clicked element.
I suspect that I might be missing something, but I suspect that your problem is using a.title instead of this.title:
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title; // or you could use the jQuery object approach: $(this).attr('title') instead
var display = "false";
e.preventDefault();
});
The problem in your original approach is that a would be parsed as a variable, which hasn't been assigned a value, nor has it been declared, so that it would return undefined or null (at best). Within the scope of the each() method, you're iterating over individual nodes; so to access the properties/attributes of that node use this.
To access any attribute of a DOM element through jQuery, you can use the .attr() function.
In your particular case you would do.
var main_id = $(this).attr('title');

Link detect and replace the other,in js

Hello
I wonder how Replace automatically links on my site
that start with:
http://site.com/00000/
to:
http://site.com/11111/
detects> replaces
CSS3 attribute "starts with" selectors help you there (and jQuery supports them on all of the browsers it supports — with native features if possible, for speed). Then just use an each loop and update the href property of the raw a element:
$("a[href^='http://site.com/00000/']").each(function() {
this.href = "http://site.com/11111/" + this.href.substring(21);
});
You can use jQuerys .attr() method. You don't need to explicitly invoke .each(), jQuery will take care of you if your selector hits multiple nodes. Since version 1.4.1, .attr() like many other setters, takes a function as argument. This function gets the index and the actual value passed in. Whatever you return from this callback is going to be the new value.
$(document).ready(function () {
$('a').attr('href', function(_, href) {
return href.replace('246619', '262257');
});
});
Demo: http://www.jsfiddle.net/qR2NU/
Reference: .attr()
<script type="text/javascript">
$(document).ready(function () {
var urlContain = new RegExp('Detect Value Here');
$('a').each(function () {
var href = this.getAttribute('href').replace(urlContain, 'Replacement here');
$(this).attr('href', href);
});
});
</script>
This code loops through every link on the page that has a href attribute once the DOM has loaded and performs the required replace:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if (href !== undefined) {
href = href.replace(/246619/g, '262257');
}
$(this).attr('href', href);
});
});
The above relies on jQuery but judging by the tags you used for your question, you are already using it.
Untested:
$("a[href^=http://site.com/00000/]").each(function() {
this.href = "http://site.com/11111/" + this.href.substr("http://site.com/00000/".length");
});

Categories

Resources