JavaScript: onclick function to change another elements onclick - javascript

Intended Functionality
I'm looking for something that operates like this:
User clicks on the img
handclick function gets called and 'enables' the parent anchor of the img
If clicked again, the anchor will redirect the user to a new page
My Issue:
The below does 'enable' the link, but it also acts as if the link was clicked at the same time.
Is there any way to fix this functionality?
HTML Code:
<a href="#Url.Action("Index/" + #card.ID)" onclick="return false;" class="link">
<img src="~/Resources/#card.Image" id="#card.ID" onclick="handClick(#((int)card.Value), #card.ID)" class="card" />
</a>
JavaScript Code
function handClick(cardValue, cardID) {
*... irrelevant code ...*
var playedCard = document.getElementById(cardID);
*... irrelevant code ...*
playedCard.parentElement.onclick = function () { return true };
}

Since I don't know what the irrelevant code is I'll stay only on the first click enable issue.
My approach includes the href attribute. without it the link doesn't work. So, what I did was change the attribute's name into something else and when clicked, replace it with the actual attribute, thus "activating" the link.
Notice that the cursor changes into a pointer after the first click.
document.querySelectorAll('a[hrefx]').forEach(function(el) {
el.addEventListener('click', function() {
// This condition enable re-using the listener for other purposes.
if (this.getAttribute('hrefx')) {
this.setAttribute('href', this.getAttribute('hrefx'));
this.removeAttribute('hrefx');
}
});
});
<a hrefx="#">
<img src="https://picsum.photos/200">
</a>
<a hrefx="#">
<img src="https://picsum.photos/200">
</a>

Related

How to pass value of href to javascript and use it in window.location when a hyperlink is clicked?

I have two types of hyperlinks .When the first one is clicked the value of href is passed to function but its value never used in window.location!(Because it opens the link in safari instead of iphone webApp ).When the second hyperlink is called the value of href never get passed to function and again the href value is opened in safari instead of webApp!Could any one help me pass value of href to function and use it in window.location instead of opening it on safari.Thanks in advance.
<li class="x"><a id="1" title="1" href="./test.php?try" onclick="myFunction(location.href=this.href);"> <img id="Button1" src="./1.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">FIRST</div></a></li>
<li class="x"><a id="2" title="2" href="./test.php" onclick="myFunction(location.href=this.href+'?try&appid='+currentID;return false;);"> <img id="Button2" src="./2.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">SECOND</div></a></li>
<script>
function myFunction(myLink) {
alert("hello"+myLink);
window.location = myLink;
}
</script>
There are several things at play here. As fiprojects points out, it's best not to do inline JavaScript (some of the reasons are just personal preference). You'll end up repeating yourself and making it hard to maintain your code (among other reasons). Your best bet is to use Event Listeners (w3schools link, not always the best resource, but is sufficient for this example). These are extremely simple if you're using a JavaScript library (jQuery). But being that you requested a JavaScript solution, I'll outline how to do that in my answer.
First, let's format your code to make it easier to read:
<li class="x">
<a id="1" title="1" href="./test.php?try" class="myLink">
<img id="Button1" src="http://placehold.it/360x240">
<div class="caption" style="color:red">FIRST</div>
</a>
</li>
<li class="x">
<a id="2" title="2" href="./test.php" class="myLink">
<img id="Button2" src="http://placehold.it/360x240">
<div class="caption" style="color:red">SECOND</div>
</a>
</li>
I've only made a couple changes here. I removed the JavaScript onclick. I created a placeholder image (just for my own purposes, as I don't have your images, you'll want to put your images back in there). And lastly, I added a class="myLink" to your <a>. This will allow us to reference your links with our event listener a bit more easily.
For the JavaScript
<script>
var linksArray = document.getElementsByClassName("myLink");
var myFunction = function(event) {
event.preventDefault();
var href = this.getAttribute("href");
alert('hello ' + href);
window.location = link;
return false;
};
for (var i = 0; i < linksArray.length; i++) {
linksArray[i].addEventListener('click', myFunction, false);
}
</script>
The first line is creating an array with any elements that have class="myLink". We will loop through this array later, and add the event listener. Before we loop through, we need to create your function.
In order to prevent the default action that occurs when a user clicks the link, we need to stop propagation. So we'll use event.preventDefault() here. I have also added return false; to the function. Both are intended to do the same thing.
Instead of passing a variable, we'll use this to obtain the reference. We'll also use the JavaScript function getAttribute and pass href to it. This will pull the href value for you.
lastly, we are looping through our linksArray. We're adding a click event listener and assigning myFunction as a callback. Now, any time that a user clicks on one of the images, this function will fire off.
And here's a working example on JSFiddle.
You are trying to run before you can walk...
Your javascript needs alot more work. Avoid putting javascript inside html. Thus avoid things like:
onclick="myFunction(location.href=this.href);"
I would use jquery (javascript library) as it would help in the long run as it would lead you to be cross browser compatible.
Your "id" tags should be alphabetic or alphanumeric, not numeric. So id="1" is (I believe) illegal even if it works.
Actually... Sorry.... but the more i think about it, you really need a good book to advance your javascript before attempting what you want to do otherwise you'll fail to understand limitations or risks to some of your work.
Using jquery (which itself is written in javascript) you could change the URL via
$("#link1").click( Change1 );
$("#link2").click( Change2 );
function Change1()
{
$("#link1").href("./test.php?try");
}
function Change1()
{
$("#link2").href("./test.php?try");
}
The above would work if your id tags were renamed from id="1" to id="link1" and id="2" to id="link2"
Sorry I not help more than that...

Best way to find nearest href attribute?

Why I don't think it's a duplicate.
Hmm, I think that's slightly different to what I'm asking. I don't
want to add a listener to all A tags, rather, substract an href
attribute, if any, on a click event's target.
I'm trying to "Ajaxify" my whole site, so that when an user clicks ANY link contained within the page, a script sends the "url" or HREF attribute (of the clicked element) to an Ajax function, which in return, renders the requested content (as indicated by the link clicked).
I need to find the HREF attribute of the clicked element, if the element is a link. The problem here, is that many elements can be contained within an A tag (because of the way I've structured them), and e.target.href doesn't necessarily always return an HREF attribute.
Here is what I have so far:
function ajaxifyLinks(e) {
var target = e.target;
e.preventDefault();
while(!target.href) {
target = target.parentNode;
}
if(target.href) {
ajaxLoad(target.href);
}
}
document.body.addEventListener('click', ajaxifyLinks);
And here are examples of different "clickable" links that I have:
<!-- Link -->
<a href="/cats">
cats
</a>
<!-- Link -->
<a href="/hello">
<span>
<span> hi </span>
</span>
</a>
<!-- Link -->
<a href="/bye">
<span>
bye
</span>
</a>
As you can see, this is why e.target.href won't always return the HREF attribute, because you are actually clicking a "linked" span element, however, the browser does take you to the link. Why does this happen? And is there any way I can benefit from that behavior? (As in, extracting the location where the browser is taking you, even if you aren't clicking over an A tag).
I don't like my solution, because the while loop just keeps looking up the DOM tree, sometimes needlessly (when e.target isn't a link or contained by a link).
Thanks.
If the element clicked does not have an href, it searches it's parents for an element that has an href. Vanilla JS solution.
function findUpTag(el, attr) {
while (el.parentNode) {
el = el.parentNode;
if (el[attr]) {
return el;
}
}
return null;
}
document.body.onclick = function (event) {
event.preventDefault();
var href = event.target.href;
if (!href) {
var closest = findUpTag(event.target, 'href');
if (closest) {
href = closest.href;
}
}
document.getElementById('output').innerHTML = 'element clicked: ' + event.target.nodeName + '<br>closest href: ' + href;
};
a,
output {
display: block;
}
<!-- Link -->
<a href="/cats">
cats
</a>
<!-- Link -->
<a href="/hello">
<span>
<span> hi </span>
</span>
</a>
<!-- Link -->
<a href="/bye">
<span>
bye
</span>
</a>
<output id="output"></output>
Use the .parent(), ref: http://api.jquery.com/parent/
for example, you can do
var hrefElem = $(target).parent('*[href]');
var link = hrefElem.attr('href');
New answer:
<!-- Link -->
<a href="/cats">
cats
</a>
<!-- Link -->
<a href="/hello">
<span style="pointer-events: none;">
<span style="pointer-events: none;"> hi </span>
</span>
</a>
<!-- Link -->
<a href="/bye">
<span style="pointer-events: none;">
bye
</span>
</a>
Just attach a click handler to each link on the page:
function ajaxify(e)
{
e.preventDefault();
ajaxLoad(this.href);
}
[].forEach.call(document.getElementsByTagName('a'), function(el) {
el.addEventListener('click', ajaxify.bind(el));
});
Have a look at What is event bubbling and capturing? to understand how events propagate through the DOM.
The technique of capturing anchor links and loading them via Ajax is referred to as Hijax. Because you're replacing content on the page, you can't simply set up a single event to handle all links, and you probably don't want to keep re-binding every page load, so the approach you are using is good, and is known as event delegation.
The last article describes exactly your problem (right at the very end), and also describes a solution similar to yours, which is really the best way to do it in this scenario. However, you could look at using a microlibrary to simplify some of the event delegation; one example is gator.js.

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

html anchor tag reference

i have an anchor tag as below.
<a style="border:0px" href='javascript:deleteAttachment(this);' />
Inside the deleteAttachment, how can i get the anchor tag. Sending this to the method, sends the window element to the method.
function deleteAttachment(ancElement){
//Jquery operation on acnElement
}
Please helop me out.
I would recommend a slightly different approach, since what you're trying to do is a bit old.
assuming you already loaded jQuery, here we go:
<a id="myFirstLink" href="someHref" />
<a class="otherLinks" href="secondHref" />
<a class="otherLinks" href="thirdHref" />
<script>
$(function() {
$('#myFirstLink, .otherLinks').click( function(event) {
// stops the browser from following the link like it would normally would
event.preventDefault();
// do something with your href value for example
alert( $(this).attr('href') );
});
});
</script>
So basically what you can do is this: simply generate all your anchors like you would normally would and apply the same class name to each of them - in my example the class would be "otherLinks".
After that, all your links will be handled by that anonymous function.
Use the onclick handler:
<a onclick="deleteAttachment(this)">
or, the cleanest and most accepted method nowadays, have just the raw link in the HTML:
<a id="deleteAttachment">
and add the click event programmatically, in a separate script block, on DOM load:
document.getElementByID("deleteAttachment").onclick =
function() { ... you can use "this" here .... }
you must set its ID attribute
<a id="myAnchor" style="border:0px;" href="javascript:deleteAttachment('myAnchor');"/>
then use jquery to find it
function deleteAttachment(ID)
{
var MyAnchor = $('#'+ID);
}

Categories

Resources