How to make both href and jquery click event work - javascript

I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>

I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.

You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();

Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle

Related

<a href preventDefault works every second time

I have a trash icon which user clicks on to delete current element from database. I want to make it work with ajax if user has javascript enabled. There are multiple items on page.
Don't know why but even after adding preventDefault, href works like regular href instead of performing ajax. It triggers ajax request without refreshing window only every second time I click on trash icon.
Do you know where is the problem?
$('.delete_bulletin').on('click', function (e) {
console.log('event');
e.preventDefault();
$.get($(this).attr('href')).done(
function () {
reloadBoardContent();
}
);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bulletin_board">
<div class="bulletin_card">
<i>4. apríl 2018 14:50</i>
<h4>NAME</h4>
<p></p><p>htrhr</p><p></p>
<a class="delete_bulletin" href="/bulletin-board/delete/35/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
</div>
<hr>
<div class="bulletin_card">
<i>4. apríl 2018 14:49</i>
<h4>NAME</h4>
<p></p><p>fdsafdfs</p><p></p>
<a class="delete_bulletin" href="/bulletin-board/delete/34/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
</div>
<hr>
</div>
I'm pretty sure (but needs confirmation) that your reloadBoardContent() is updating the div where this <a> is located.
If that's the case, the anchor will be replaced and the event won't trigger to the newly created ones.
The solution is to use delegate events, which will make it work for dynamically added elements.
Do this instead:
$('#bulletin_board').on('click', '.delete_bulletin', function (e) {
If you don't replace the <div id="bulletin_board" itself but only its contents, everything shall be fine from now on.

How to change a word in a h2 when certain page is clicked on

I'm trying to change a certain word in the title of a page dynamically with javascript depending on which link in the nav is clicked on. So for instance, if the "Asia" link is clicked I want the h2 to display: "You are in Asia" or if the "Europe link is clicked I want the h2 to say: "You are in Europe."
The html for the nav bar:
<div id="zone-nav">
<a href="" id="surge-btn"</a>
<a href="" id="latin-btn"</a>
<a href="" id="africa-btn"</a>
<a href="" id="asia-btn"</a>
</div>
The html I have thus far for the title that needs to be changed: `
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>`
I know I need to write a function to determine what link is pressed, but I am a little confused on how to approach this.
if you add some extra markup to your html, you can use a single jQuery event handler:
<div id="zone-nav">
<a class="zone-select" href="" id="surge-btn">Surge?</a>
<a class="zone-select" href="" id="latin-btn">Latin</a>
<a class="zone-select" href="" id="africa-btn">Africa</a>
<a class="zone-select" href="" id="asia-btn">Asia</a>
</div>
now the event handler:
$(document).ready(function() {
$(".zone-select").on("click", function() {
$("#zoneName").html($(this).html());
};
});
Firstly you need to deal with your duplicate id here:
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>
Note we cannot have the same id otherwise we don't know how to get an element by it's id. So remove the uneeded one on the h2:
<h2>You are in <span id="zoneName"></span></h2>
Then add event's to your a tags:
<div id="zone-nav">
<a onclick="update('Surge')" id="surge-btn" >item1</a>
<a onclick="update('Latin')" id="latin-btn" >item2</a>
<a onclick="update('Africa')" id="africa-btn" >item3</a>
<a onclick="update('Asia')" id="asia-btn" >item4</a>
</div>
Note: This can be done purely in JavaScript or be done easily in jQuery. But since you did not mention it I will not be using jQuery. We could iterate through by ClassName and have the links be a class, but that's no more simple then the way above.
For the JavaScript we need to return false to prevent the default behavior of a anchor tag:
function update(text) {
document.getElementById("zoneName").innerHTML = text;
return false;
}
Here is a working Fiddle
Would there be a way to keep the updated text in the even if the page reloads?
Yes there is a way to do this without having to use a server-sided language. What I will do is use HTML 5 web storage, note this will only work for browsers that support HTML 5 (which is all of the modern ones), you can use cookies if you need support for older browsers that work similarly for the following example. In this case I will be using sessionStorage which saves the information even until the browser is closed.
I will emulate a href to the same page for the <a> tags, we need to do this because we need to save out information before we move to a new page. After I save I will call location.reload() that will act as a refresh. Note that you could make this move to an entirely new page as well, just include the script on the new page and use window.location.href = "newPageUrl" ( jsfiddle prevents me from moving to a new page ).
The HTML will be the same but the JavaScript will be updated as followed:
window.onload = function() { // When the page loads
if(sessionStorage.zoneName) { // Check if the session exist
// update the page with the session info
document.getElementById("zoneName").innerHTML = sessionStorage.zoneName;
}
}
function update(text) {
sessionStorage.zoneName = text; // store the text into a session called "zoneName"
location.reload(); // reload the page
return;
}
Here is a working Fiddle
Here's an example of what you could do for the africa-btn (this will require jQuery, I hope that's alright):
$(document).ready(function() {
$("#africa-btn").on("click", function() {
$("#zoneName").html("Africa");
};
// Other buttons here
});
What this is doing is attaching an action to the "click" event of the africa-btn anchor tag. When it's clicked it should update the span's html as described above. You can add further click events in a similar way.
Using $("#africa-btn") to bind the click event is a way to do it specifically for that one button, so you'll have to do it for each id.
This would update the selected zone in the dom
<div id="zone-nav">
<a id="africa-btn" onclick="updateZone('africa'); return false;"> </a>
<a id="asia-btn" onclick="updateZone('asia'); return false;"> </a>
</div>
function updateZone(countryName){
document.getElementById('zoneName').innerText = countryName;
return false;
}
are you looking for something like this :
Simple html and javascript only:
http://jsfiddle.net/q9L37c32/
Asia

<a> onclick function not working

My function is not fired when the tag is clicked. Here is my code:
HTML:
<div data-role="footer">
<div data-role="tabstrip" id="tabs">
Home
Settings
<a onclick="signOff()" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
</div>
</div>
JavaScript:
function signOff() {
console.log("something");
VCare.VCareWebService.signOff({cache:false,
callback:function(xml) { // invoke the service
// use jQuery to extract information we are interested in
console.log(xml);
}
});
}
You can't have both an onClick function and valid href attribute in <a>.
Change your anchor element to:
<a onclick="signOff()" href="javascript:void(0)" data-icon="settings" id="contacts">Log Out</a>
You can redirect the page using javascript if you want to.
Another way is to make sure that your onclick returns a false to stop the default event from running.
<a onclick="signOff(); return false" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
Or..
<a onclick="return signOff();" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
function signOff() {
console.log("something");
VCare.VCareWebService.signOff({cache:false,
callback:function(xml) { // invoke the service
// use jQuery to extract information we are interested in
console.log(xml);
}
});
return false;
}
you need to change your A tag to
<a href="javascript:signOff();
window.location = "views/home.html" data-icon="settings" id="contacts">Log Out</a>
I would recommend not using the onclick method. Not only does it apparently conflict with the default href operation, but it can also cause some minor visual issues where clicking in the margins of the element, etc., can call the function without highlighting the text the way you would expect in a normal link.
Instead, use:
Log Out
Then just change the page address programatically in the signOff function, using this.document.location.href = location or similar
EDIT: it's looking like window.location works better. +1 for Omar, looks like he has the same answer

Display href link into div

I want to display the href link in the <div id="display"></div> tag so when I press anything in the menu or in my list it'll just open in the div with display as its id.
I have this menu like this done
<div class="menu">
HOME
</div>
<div id="display"></div>
and my JavaScript is like this
$('#display').html($('.menu a').html());
I don't know much about javascript, but I think the javascript code is actually wrong, I would appreciate is someone would help me.
I want to display the href
You need to fetch href property for that you can use .prop()
$('#display').html($('.menu a').prop('href'));
Demo
In case you mean retrieve the page and place it in the div:
// bind click event to all anchors within .menu
$('.menu a').click(function(e){
// fetch the page using AJAX and place the results in #display
$('#display').load(this.href);
// prevent navigating away from the page (default action of anchor)
e.preventDefault();
});
(Or maybe it's just me, but the question seems very hard to understand. :shrug:)
$('.menu a').on('click',function(e){
e.preventDefault(); //this will keep your link from loading
var href = $(e.currentTarget()).attr('href');
$('#display').html(href);
});
We can use an iframe to display the link in the <a> tag.
Here's a fiddle
Here is my version...
HTML
<div class="menu">
<a id="xxx" href="http://stackoverflow.com" onkeydown="myFunc()">HOME</a>
</div>
<div id="display"></div>
JS
$(document).ready(function() {
var data = $("a#xxx").attr("href");
$('#display').html(data);
});

Fancybox 2.0 not working, very simple first test

My page is at www.danielcw.info.
At the bottom I am calling:
$(document).ready(function() {
$("#single_1").fancybox({});
});
On:
<div id="single_1">
TESTTESTEST
</div>
Nothing happens. Can anyone please explain where I am going wrong, I see all the JS and CSS loaded and on the page.
Thank you,
Daniel
Typically, Fancybox is initialized on an anchor tag which points to a div element or a link housing the content to be shown on the Fancybox:
HTML:
Click here to launch Fancybox
<div style="display:none">
<div id="single_1">
Content goes here
</div>
</div>
Javascript:
$(function(){
$('a#fancybox').fancybox({
// Fancybox options here
})
.trigger('click'); //Optional - if you wish to trigger the Fancybox after initialization
});
Try using,
$(document).ready(function() {
$("a #single_1").fancybox();
});
<a id="single_1" href="#">
TESTTESTEST
</a>
You've merely instantiated the plugin. You have to trigger it now.
So you can add any DOM element and watch for an event then trigger the plugin.
Click me
The JS
$('fancyme').on("click", function() {
$.fancybox('#single_1');
});
OR
You can trigger on page load
$(function(){
$.fancybox('#single_1');
});

Categories

Resources