return false not preventing click - javascript

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);
});

Related

Get data attr value on hover

I have a few links. When I hover mouse over the links I would like to get the values stored in data attributes. I need to pick the t values and pass them into function
HTML
<a href="#" data-lat="23.333452" data-lon="-97.2234234">
JS
var loc = document.querySelectorAll("a[data-lat]");
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
function locOver() {
// do something
}
function locOut() {
// do something else
}
It's been a while since I used vanilla JS and it's been a long day so I'm sure it's pretty close but I'm stuck. I keep getting:
Uncaught TypeError: loc.addEventListener is not a function
What am I missing here?
You need to loop through the nodes that you obtained with document.querySelectorAll("a[data-lat]") for adding events.
Working example.
Node
<script>
var loc = document.querySelectorAll("a[data-lat]");
loc.forEach(node => {
node.addEventListener("mouseover", locOver);
node.addEventListener("mouseout", locOut);
})
function locOver(event) {
// do something
console.log('mouseover', event.target.dataset)
}
function locOut() {
// do something
console.log('locOut')
}
</script>
const loc = document.querySelector("a[data-lat]");
const locOver = () => {
console.log("Mouse is over the link");
}
const locOut = () => {
console.log("Mouse is out of the link");
}
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
Link
Explanation:
I target the link using .querySelector method that returns a single node.
After that i created two event handler for mouseOver and mouseOut and than i added the eventListener to the link.

modify url by clicking a div

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');

JavaScript function not giving the right output

This is a section of my view in which I want the result to show.
Can any one solve this problem?
When this.waitlist works, it should return the container like div#sntq-waitlist but it gives object[ ] instead.
Can anyone tell me why this is?
JavaScript
initLiveWaitList: function() {
this.waitlist_ = $('sntq-waitlist');
this.daily_status_ = $('sntq-daily_status');
this.waiting_ = $('sntq-waiting');
this.seated_ = $('sntq-seated');
this.oneFour_ = $('sntq-one-four');
this.fiveSix_ = $('sntq-five-six');
this.seven_ = $('sntq-seven');
this.running_ = true;
this.loadWaitList_();
this.intervalId_ = this.loadWaitList_.periodical(1200000, this);
window.addEventListener('focus', function() {
if (!this.running_) {
this.loadWaitList_();
this.intervalId_ = this.loadWaitList_.periodical(1200000, this);
}
}.bind(this));
window.addEventListener('blur', function() {
clearInterval(this.intervalId_);
this.running_ = false;
} .bind(this));
},
View
<div id="sntq-daily_status">
<div class="loading"></div>
</div>
I donĀ“t think I completely understood your question, but to me it looks like you are using jQuery to get the containers at the top of your code.
If this is the case you are probably just missing the ID selector.
Try to change the code to
this.waitlist_ = $('#sntq-waitlist');
this.daily_status_ = $('#sntq-daily_status');
//[...]
(note the "#" selector if you want to look for elements by ID, which seems to be the case in your example).

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.

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