modify url by clicking a div - javascript

I have a page in php, and I'm trying to add an ?id=variable_value extension to it's url when I click on a div, but when I click it gives me an undefined url error with the extension
Here is the script:
<script language="javascript" type="text/javascript">
var Pokemon_ID = 1;
function changeUrl() {
location.href=this.href+'?id='+Pokemon_ID;return false;
}
document.getElementById( 'right-btn' ).onclick = function() {
changeUrl();
};
</script>
And the div :
<div id="right-btn" href="pokedex.php" onclick="changeUrl()">

Don't use two separate ways of attaching handlers when you only need one. Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead.
The problem is that when assigning the handler via onclick, the this in changeUrl is undefined, because the calling context is global. Feel free to avoid using this when it can cause confusion.
Just use addEventListener alone. Also, you'll have to use getAttribute('href') instead of .href because divs are not supposed to have href properties.
const Pokemon_ID = '5';
document.getElementById('right-btn').addEventListener('click', function(e) {
// location.href = e.target.getAttribute('href') + '?id=' + Pokemon_ID;
console.log('changing URL to ' + e.target.getAttribute('href') + '?id=' + Pokemon_ID);
});
<div id="right-btn" href="pokedex.php">text</div>

Try this instead:
location.href += '?id=' + Pokemon_ID;

Because you call changeUrl() within the onclick method you loose the context of this. This in changeUrl is not your div. Maybe you have to pass this into the method with changeUrl(this) or you just pass the href with changeUrl(this.href).
Than use:
function changeUrl(target){
location.href=target.href+'?id='+Pokemon_ID;
}

As mentioned by CertainPerformance above, you are not passing the right arguments to you function to work correctly; Using you code as a reference, you can either pass the original event to you changeUrl() function, then use the e.target to get to your 'right-btn' element.
Javascript:
var Pokemon_ID = 1;
function changeUrl(e) {
var href = e.target.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl(e);
};
HTML:
<div id="right-btn" href="pokedex.php">Click Me 4</div>
However, if you realy want to use this in your function to refer to the 'right-btn' element, then you can change the code to;
Javascript:
var Pokemon_ID = 1;
function changeUrl() {
var href = this.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl.call(e.target);
};
The changes being the call in the event handler:
changeUrl.call(e.target);, which calls you function in the 'context' of the e.target, making the this in your changeUrl() function to the element. Then you can use the this as in var href = this.getAttribute('href');

Related

return false not preventing click

I have this jquery to prevent click , but its not working , why ?
HTML
<a href="page.htm?action=addtofav&id=556" class="fav-auto">
<div class="favno button-com color">Favorite</div></a>
Javascript
$(document).ready(function() {
$(document).on("click","a.fav-auto",function(e) {
$.get($(this).attr("href"),function(fav-lin) {
var fav-pos = $(fav-lin).find('.fav-mess-in');
var fav-pis2 = $(this).attr("href");
$('fav-mess').empty();
$('fav-mess').append(fav-pos);
$('fav-mess').append(fav-pos2);
});
return false;
});
});
return false does work perfectly, but you have some syntax errors in your code.
First, I think that $('fav-mess') should be either a class $('.fav-mess'), or id $('#fav-mess') selector, not a tag selector.
Next, You have to change fav-pos, fav-pos2 and fav-lin variables.
You cannot use - (minus) operator in variable declaration - this is a syntax error (javascript interpretes them as math operation : favminuspos):
var fav-pos = $(fav-lin).find('.fav-mess-in');
var fav-pos2 = $(this).attr("href");
Replace them to something like this (used class on 'fav-mess' element since I'm not sure what you're selecting):
$.get($(this).attr("href"),function(fav_lin) {
var fav_pos = $(fav_lin).find('.fav-mess-in');
var fav_pos2 = $(this).attr("href");
$('.fav-mess').empty();
$('.fav-mess').append(fav_pos);
$('.fav-mess').append(fav_pos2);
});
PS. Use chaining whenever you can, so that you don't unnecessarily traverse the DOM multiple times for a single element:
$.get($(this).attr("href"),function(fav_lin) {
var fav_pos = $(fav_lin).find('.fav-mess-in');
var fav_pos2 = $(this).attr("href");
// chain the element manipulation:
$('.fav-mess').empty().append(fav_pos).append(fav_pos2);
});

If var not set always results in true, even if its set

Not sure how to formulate this but here it goes.
I am checking if a var exists (content), if it doesnt i set it.
Problem is next click, it still behaves as if there is no var content. But why??
Here my code:
$("#nav a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content)
{
var content = $('<div>').load(load);
$(".content").append(content);
}
else
{
var position = content.offset();
$(document).scrollTop(position);
}
});
It never results to else, so always a click is made the whole load and append function repeats.
Basically how can I record that content for this particular link has been loaded once, so the else function should be performed next time?
Also, what is wrong with my if(!content) statement? Is it because of scope?
In Javascript functions determine the scope of an object. You need to place content in the global scope. Currently it is created within the anonymous function assigned to the click event handler, so when the function is executed again content is out of scope causing it to return false.
var content;
$("#nav a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content)
{
content = $('<div>').load(load);
$(".content").append(content);
}
else
{
var position = content.offset();
$(document).scrollTop(position);
}
});
Try to make the var content as a global variable rather than a local one, like you are doing right now. That's why the if (!content) result as true always, like:
var content;
$("#nav a").click(function (event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
if (!content) {
content = $('<div>').load(load);
$(".content").append(content);
} else {
$(document).scrollTop(content.offset());
}
});
Just to show what happens, when value of content is not set at first and then set again:
var content;
console.log(content); // undefined
console.log(!content); // true
content = 'text';
console.log(content); // text
console.log(!content); // false
Thanks to everyone for answering the first question about the checking if var exists.
I ended up ditching this whole concept it turned out the
one()
function is what I needed all along. In order to only execute a function once and another function on all following clicks.
Here it is:
$(document).ready(function() {
//Ajaxify Navi
$("#nav a").one("click", function(event) {
event.preventDefault();
var href = $(this).attr("href");
var load = href + " .content";
var content = $('<div>').load(load);
$(".content").append(content);
$(this).click(function(event) {
event.preventDefault();
var position = content.offset().top;
$(document).scrollTop(position);
$("body").append(position);
});
});
});
What this is is the following:
1st click on a button loads content via ajax and appends it, second click on the same button only scrolls to said content.

Calling onClick events

I'm having a problem with my code, lemme first paste my code, most of it isn't important, just the context of it.
$("#navbar > a").click(function(event) {
$('#controls').show();
var currentNum = parseInt($(this).attr('class'), 10);
document.getElementById('pNum').innerHTML = "pg. " + (currentNum + 1);
event.preventDefault();
var t2 = ($(this).attr('id')).split("#");
var $tr = $(zip.file(localStorage.selected + "/" + t2[0]).asText());
document.getElementById('main').innerHTML = "";
$('#main').append($tr);
document.getElementById(t2[1]).scrollIntoView()
current = ($(this).attr('class'));
$(function() {
$("#main img").each(function() {
var imgPath = localStorage.selected + "/" + $(this).attr('src');
var imageData = zip.file(imgPath).asBinary();
$(this).attr('src', 'data:image/jpeg;base64,' + btoa(imageData));
});
});
$("#main a").click(function(event){
event.preventDefault();
var elems = ($(this).attr('href')).split("#");
var $path = $(zip.file(localStorage.selected + "/" + elems[0]).asText());
document.getElementById('main').innerHTML = "";
$('#main').append($path);
});
});
Now the click event at the bottom only works if I place it inside the code that creates the content, which shouldn't be the case and secondly it only works once, after I call it for the first time it refuses to work, any suggestions ?
It sounds like you want to use event delegation instead. For example:
$(document).on('click', '#main a', function(event){
event.preventDefault();
var elems = ($(this).attr('href')).split("#");
var $path = $(zip.file(localStorage.selected + "/" + elems[0]).asText());
document.getElementById('main').innerHTML = "";
$('#main').append($path);
});
The problem is that the $('#main a').click(...) approach requires that the #main a elements already be present on the page at the time that the click handler is bound.
Event delegation allows you to listen for a click event on the document (or any other element that will always be present), and see if that event originated from a #main a element. This allows you to add/remove elements on the fly without worrying about which ones have or haven't already had click handlers bound.
I've had this problem before, have you tried using this?:
$("<element id>").on( 'click', this, function ()
{
// Your code here
}
reference: http://api.jquery.com/on/
edit* Sorry did not see an answer before ( better explanation in answer above ) - but I'll keep mine for reference.

jQuery getting ID of clicked link

I have a modal box in jQuery which I have created to display some embed code. I want the script to take the id of the link that is clicked but I can't seem to get this working.
Does anyone know how I can do that or why this may be happening?
My jQuery code is:
function generateCode() {
var answerid = $('.openembed').attr('id');
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<code><iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '" frameborder="0"></iframe></code>');
}
$(document).ready(function () {
$('.openembed').click(function () {
generateCode();
var answerid = $('.openembed').attr('id');
$('#box').show();
return false;
});
$('#embed').click(function (e) {
e.stopPropagation()
});
$(document).click(function () {
$('#box').hide()
});
});
My mark-up is:
Embed
Embed
Your problem is here:
$('.openembed')
returns an array of matched elements. Your should instead select only the clicked element.
$('.openembed') works correctly if you assing a click event to all elements that have this class. But on the other hand, you're unable do know which is clicked.
But fortunately in the body of handler function click you could call $(this).
$(this) will return the current (and clicked element).
// var answerid = $('.openembed').attr('id'); // Wrong
var answerid = $(this).attr('id'); // Correct
// Now you can call generateCode
generateCode(answerid);
Another error is the body of generateCode function. Here you should pass the id of selected element. This is the correct implementation.
function generateCode(answerid) {
if($('#embed input[name="comments"]:checked').length > 0 == true) {
var comments = "&comments=1";
} else {
var comments = "";
}
$("#embedcode").html('<iframe src="embed.php?answerid=' + answerid + comments + '" width="550" height="' + $('#embed input[name="size"]').val() + '"frameborder="0"></iframe>');
}
Here I have implemented your code with the correct behavior: http://jsfiddle.net/pSZZF/2/
Instead of referencing the class, which will grab all members of that class, you need to reference $(this) so you can get that unique link when it is clicked.
var answerid = $(this).prop('id');
$('.openembed').click(function () {
generateCode();
var answerid = $(this).attr('id');
$('#box').show();
return false;
});
Use $(this). $('.openembed') refers to multiple links.
var answerid = $('.openembed').attr('id');
needs to be
var answerid = $(this).prop('id');
The other answers are trying to fix the click() function, but your issue is actually with the generateCode function.
You need to pass the clicked element to the generateCode function:
$('.openembed').click(function () {
generateCode(this);
And modify generateCode:
function generateCode(element) {
var answerid = element.id;
Of course var answerid = $('.openembed').attr('id'); within the click code isn't correct either, but it doesn't seem to do anything anyway.
Get the id when the correct anchor is clicked and pass it into your generateCode function
$('.openembed').click(function () {
var answerid = $(this).attr('id');
generateCode(answerid)
$('#box').show();
return false;
});
Change your function
function generateCode(answerid) {
// dont need this line anymore
// var answerid = $('.openembed').attr('id');

how to add onclick event on anchor tag that is generated with javascript?

I'm using only javascript, not jQuery or no other javascript frameworks.
I have created one anchor tag like:
var _a = document.createElement('a');
now I want to add onclick for this tag. I have tried following:
_a.onclick = function(){ mycode(id); }
The function applies on that but the anchor tags are create in loop... so mycode(id) is always taking the last value of the loop.
Can any one help me out in this ?
try following:
_a.onclick = (function(id){return function(){ mycode(id); }})(id);
Probably you need a function to create your handler like this:
function createHandler( id ) {
return function(){ mycode( id ); };
}
and then assign inside the loop
for ( i= ... ) {
_a.onclick = createHandler( i );
}
On the other hand you maybe should use addEventListener() (MDN docu) to add events to elements:
_a.addEventListener( 'click', createHandler( i ) );
for(var id = 0; id < 10; id++){
var _a = document.createElement('a');
_a.onclick = (function(id){
return function (){
mycode(id);
}
})(id);
}
That should fix it.

Categories