Help needed in Javascript + Image + HREF - javascript

In the above code, I am appending a javascript onclick method to the image tag. When I click the image once and I press back, it should go back to the page it came from. Instead its staying on the same page. Is there any way I can avoid that? (probably set something else instead of href="#"). The reason I set href="#" is to make my cursor turn into hand, other than that it has no use.
This is occuring in Firefox. In IE it works fine.
Please help. Thanks.

The reason I set href="#" is to make
my cursor turn into hand, other than
that it has no use.
You can remove the <a href="#"> and add the cursor: pointer style to the image:
<img src="logo.gif" style="cursor: pointer;" />
... to turn the cursor into a hand.
On the other hand, it is probably better to follow the guidelines for progressive enhancement, as David suggested in another answer.

<img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi'); return false;"/>
you need add return false; to your onclick events if you don't want to load the link.

<a href="#">
<img src="http://www.google.com/intl/en_ALL/images/logo.gif"
onClick="alert('hi'); return false;"/>
</a>
return false prevents the default action from occurring (in this case navigating to "#"), and then navigating back will return you to the previous page, instead of to the current page without "#".

Follow the pragmatic guidelines for progressive enhancement. In particular: Build on things that work.

Use this instead:
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi')" style="cursor:pointer"/>

Related

How should I not load the images with broken link?

I'm working on a feature, in which images are being rendered from the servers. I was working on aligning the images but found that there is a lot of white space. This was the reason, due to loading of images with a broken link.
HTML :
<div class="image-result" *ngIf="Display('images')">
<div class="col-sm-3" *ngFor="let item of items$|async">
<a href="{{item.link}}">
<figure>
<img class="res-img" src="{{item.link}}" onerror="this.style.display='none'">
</figure>
</a>
</div>
</div>
I have used onerror="this.style.display='none'" to solve the problem, but leaves a lot of white space when images are being loaded from the server. Is there any solution for it like to remove img tag whenever a image with a broken link has been detected ? I have gone through stackoverflow before asking question, but I'm not able to solve this problem. It would be great if someone can help me out. Thanks! :)
Instead of onerror="this.style.display='none'" to hide an image, you can use onerror="this.parentNode.removeChild(this)" to remove the image tag altogether.
If you want to remove the entire column, in your specific case you can do the following.
var colEl = this.parentNode.parentNode.parentNode;
colEl.parentNode.removeChild(colEl);
Or, in your HTML:
onerror="this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)"
You should probably move that to some JavaScript function and attach your handler by saying
element.addEventListener('error', function() { /* ... */ });
References: parentNode, removeChild, addEventListener.
If you don't care about supporting Internet Explorer, you can also use remove instead of doing the parentNode.removeChild trickery. That would be particularly useful for reducing the code length in your onerror attribute, would you choose to use it, but I don't recommend that.
A more angular-way of doing this would be:
<img src="{{item.link}}" (error)="item.brokenImage=true">
So you would have:
<div class="col-sm-3" *ngFor="let item of items$|async">
<div *ngIf="!item.brokenImage">
<a href="{{item.link}}">
<figure>
<img class="res-img" [src]="item.link" (error)="item.brokenImage=true">
</figure>
</a>
</div>
</div>
You need to listen for the error event of the image element, and assign a boolean on whether the image loaded successfully or not. Then, depending on that value angular will either show the image with the div, or remove it from the DOM.

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...

Google Tag Manager - CSS selector challenge

I am trying to get the URL of a link in the source code. The challenge is that the URL is hidden behind a image, and thus only letting me fetch the image-url.
I've been trying to figure a way to solve this issue by using the new CSS selector in the trigger system and also made a DOM variable that should get the URL when the image is clicked. There can also be multiple downloads.
Here is an example of what I am trying to achieve:
<div>
<div class="download">
<a href="example.com/The-URL-I-Want-to-get-if-top-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Another-URL-I-Want-to-get-if-middle-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
<div class="download">
<a href="example.com/Last-URL-I-Want-to-get-if-bottom-image-is-clicked.pdf" target="_blank">
<img src="some-download-image.png"/></a>
</div>
</div>
There are much code above and below this snippet, but with the selector it should be fairly easy to get the information I want. Only that I don't.
If anyone have met this wall and solved it, I really would like to know how. :)
This is one possible solution. So as I understand it, you would like to grab the anchor element's href attribute when you click the "download" image.
A Custom Javascript variable would need to be created so that you can manipulate the click element object:
function(){
var ec = {{Click Element}};
var href = $(ec).closest('a').attr('href');
return href;
}
So you will need to do your due diligence and add in your error checking and stuff, but basically this should return to you the href, and then you will need to parse the string to extract the portion that you need.

How to edit text for a link that does not have an ID using Javascript

I want to change the text of a link using javascript. The problem is this particular link does not have an id. I am unable to change the html, as this is a SharePoint page, and this particular link is created by a page layout, which I do not have access to. Using IE Developer Tools, I see that the HTML surrounding the link is this:
<span id="DeltaPlaceHolderPageTitleInTitleArea">
<span>
<a href="#ctl00_PlaceHolderPageTitleInTitleArea_ctl00_SkipLink">
<img width="0" height="0" style="border-width: 0px;" alt="Skip Navigation Links" src="" /></a>
<span>
<a title="State-Compliance" href="/sites/tax/Compliance/SitePages/State-Compliance.aspx">State-Compliance</a>
</span>
<a id="ctl00_PlaceHolderPageTitleInTitleArea_ctl00_SkipLink"></a>
</span>
The link I wish to change is the second one, the one with "State-Compliance" for the tooltip.
I looked at jQuery, and found I could use $('#DeltaPlaceHolderPageTitleInTitleArea').find("a").text("Test"); to change the text, but it changes the text of all three links. How can I change just the one? Do I need to iterate through the three, or is there an easier way of getting the link I wish to change?
Sorry if this is a stupid question, I'm a c# developer, and this is my first experience using javascript.
Let me know if you need more information.
Warren
Use .eq():
$('#DeltaPlaceHolderPageTitleInTitleArea').find("a").eq(1).text("Test");
jsFiddle example
How about this, using the attribute equals selector:
$('#DeltaPlaceHolderPageTitleInTitleArea a[title="State-Compliance"]')

Firefox link to javascript function opens a new window when not intended

I have this problem where when I have this html in firefox it opens a new window
<a style="float:right;"
href='javascript:window.location.href="#";'onClick="javascript:addNewRecord();">
New Record</a>
I have tried self.location, window.location, #body, and #h1 as the href.
Originally I had the code as, but in firefox that did not do anything but open a fresh window, and not perform my function. The code works perfect in chrome.
<a style="float:right;" href="javascript:addNewRecord();">New Record</a>
The canonical inline way is
<a style="float:right;" href="#"
onClick="addNewRecord(); return false">New Record</a>
or better:
<a style="float:right;" href="#"
onClick="return addNewRecord()">New Record</a>
where addNewRecord returns false at the end of the function
An even better way is
window.onload=function() {
document.getElementById("addLink").onclick=addNewRecord;
}
function addNewRecord() {
...
return false;
}
plus
<style>
#addLink { float:right }
</style>
and
New Record
Since abusing the HREF on a link going nowhere just to get a pointer is frowned upon, you may consider a <span> with an onclick and a cursor:pointer. It does need more effort to make such an element accessible to for example screen readers.
try :
onClick="addNewRecord();return false"
How your code behaves depends entirely on what the addNewRecord() function does (including what it returns).
Without seeing inside that function it's hard to tell, but I'd say that what is happening is inside there.
Note that what you put in the href="" part probably is not affecting the behaviour you're seeing.
Try this
<a onclick="javascript:addNewRecord();">New Record</a>

Categories

Resources