I have a script which is located in its own .js file, which I believe is used to look for a specific anchor and assign an onclick event where it will forward the user to another page.
$(document).ready(
function () {
"use strict";
$(".popup a").on(
'click',
function (event) {
event.preventDefault();
$("#the_link").click();
}
);
}
);
What does #the_link mean in the context of the rest of the code? I am trying to find out how and where it is getting its value from but I can't find it anywhere. Help!
I also replaced #the_link with www.google.com, but then after nothing happened where before a window pops up. What could I do to make it go to google? <-- testing purposes.
PS. I am very very new to javascript.
PSS. In honesty, I am not sure what is going on in that code above.
That is jquery, not plain javascript (so you might add the jquery tag to your question).
$() is jquery, and the # means get me the element with the id of "the_link". Go search your document for an id="the_link", there will be no # in the id field, the # is used to tell jquery you are querying by element id, as opposed to some other type of query (by other attribute, by class, etc).
In a valid HTML document, exactly one element may have a given id, so selecting by # is a way to refer to a unique element in the document.
$("#the_link") is jquery syntax, and it refers to the element with an id of "the_link" that is located in the HTML markup.
Somewhere in the HTML, you have (for example):
<a id="the_link" href="#">...</a>
Here, the href attribute is where you would insert the http://google.com to go to that link when the anchor element is clicked.
<a id="the_link" href="http://google.com">...</a>
Alternatively you can write in your javascript:
function (event) {
event.preventDefault();
window.location.href = 'http://google.com';
}
It means that you are accessing element with id the_link. Some of your elements in html has attribute id="the_link".
If you want to go to google.com when the_link is clicked:
document.getElementById("the_link").onclick = function(){
window.location.href="http://google.com" //this goes to google.com
};
Related
I use a library which let me define href property on my links. But this lib don't allowed to define onclick property.
I want to execute JS function in my link. So I defined the following line (I know it's a bad practice, but I've no choice) :
Link
With this line, the JavaScript function runs correctly. But I need to get the element that fired the link clicked and the preceding code gives me Window object. I know href property doesn't fire an event but I really need to get the link clicked.
With button tag it's very simple by using onclick="get_element(this)" but with a tag I don't know how to do that.
If you want to try examples : https://jsfiddle.net/j8o7qvz2/
Do you have a solution ?
You can add this piece of Javascript code after generating all anchor tags. This will iterate to all anchor tags then set the onclick attribute based on the href then sets the href to #.
var links = document.getElementsByTagName('a');
for(var link of links) {
link.setAttribute('onclick', link.href);
link.setAttribute('href', '#');
}
function get_element(element) {
console.log(element);
}
Link
<br />
<button onclick="javascript:get_element(this);">BUTTON</button>
EDIT:
Since you can use external JS then maybe I'll add an answer with jQuery.
I don't know how jQuery does it may it iterates also but this is cleaner and shorter than Vanilla JS.
$('a').attr('onclick', $('a').attr('href'));
$('a').attr('href', '#');
function get_element(element) {
console.log(element);
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
Link
<br />
<button onclick="javascript:get_element(this);">BUTTON</button>
I have an anchor link on home.php which goes link this:
<a href='#?id=$thought_id' class='toggle-comment' data-id='$thought_id' '> Comments ($num_of_comments) </a>
When hovering over this anchor link, I expect to see results like this:
localhost/#?id=210
But what I am getting it this:
localhost/home.php#?id=211
I have seen a similar question here: But, having applied what the best answer suggests, I still get the same results. I also have the exact same anchor link present on profile_page.php and it works perfectly there.
The anchor link is not meant to go anywhere, on click, it dynamically enlarges the div below it, showing comments.
Edit:
How anchor link works:
when clicked, the anchor link expands the div below it. When clicked, this div appears: echo "<div id='toggleComment$thought_id' class='new_comment'>";
Then for each new comment added to this thought, another div is echo'd
<div class='new_comm' id='thoughtId".$thought_id."-childId".$comment['id']."'>
JavaScript to achieve this:
$(function() {
$("a.toggle-comment").on("click", function(event) {
// prevents browser to go to href's #
event.preventDefault();
// uses Jquery's data() function to get comment id from link's data-id attribute
var id = $(this).data('id');
// get element by id and toggle display
var ele = document.getElementById("toggleComment" + id);
$(ele).toggle();
});
});
Edit 2:
Came to a conclusion with Rocki in chat. The issue was that I have the JavaScript defined twice, once in the source code of home.php and once in functions.js which was also in the head of home.php. Removed the script from the source code, and code began to function.
Everything behind # is interpreted as the hash fragment and not send to the server. Instead your browser change the hash fragment for the current page.
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax
The character "#" is excluded because it is used to delimit a URI
from a fragment identifier in URI references (Section 4).
https://www.rfc-editor.org/rfc/rfc2396
use
<a href='/#?id=$thought_id' class='toggle-comment' data-id='$thought_id' '> Comments ($num_of_comments) </a>
instead (added / before your url)
I have somewhere on website a specific text, let's say "NewYork", and I want to fire a Google Analytics event to track all the occurrences of this string.
For example if a visitor come to a webpage that contain the string 'NewYork', I want to send a Google Analytics event.
Text string is in a span tag as <span class="city">NewYork</span>
I do not know any JavaScript codes, just tried the following code adapted from someone else. And it is not working at all.
<script>
var htmlString = $('body').html().toString();
var index = htmlString.indexOf("NewYork");
if (index != -1)
{ ga('send', 'event', 'yesNewYork', 'foundnewyork'); } </script>
Does anybody know how to do this?
Possibly a jQuery solution?
Your approach is correct in principle, but can be improved upon.
You are already using jQuery syntax so I just assume jQuery is available.
First I would suggest you follow Lars Graubner suggestion and select a more specific element and grab the text content instead of the html (as the name suggests the text()-function does not return HTML markup but text only).
$('.city').text()
will adress the span from your example - the dot in the selector says "Look for elements with a classname of".
This will actually return all elements that have the class, but for your use case that does not matter much.
However you must make sure that the text is actually rendered on the page before you call your jQuery selector; if you place it in the head of the page the text isn't there yet when the event tracking runs and thus your selector will return nothing.
You can either put the script in the footer of the page, or you can wrap it into jQuery's document.ready-call. This makes sure that the function only runs after the DOM of the document has rendered (meaning that the page structure is complete, event if images and other assets are not yet loaded. Text will be present at this point). So this would look like this:
$( document ).ready(function() {
var myString = $('.city').text();
if(myString.indexof('NewYork') > -1) {
ga('send', 'event', 'yesNewYork', 'foundnewyork');
}
});
(Obviously this assumes you have jQuery included).
If this still doesn't work you need to be more specific as to the actual error your are getting.
I have the following link, which I need to use in a Wordpress/OptimizePress based site.
Click Me
The problem is that the OptimizePress LiveEditor will strip out the javascript. So you are left with this:
<a>Click Me</a>
I'd like to attach the above javascript after the page has loaded. I have three such links (forms) on this page. Each will have the same javascript. I was thinking maybe provide unique IDs for each but I'm not sure what is the best way to do this. Any ideas?
You can get onClick attribute value on Dom ready & store it into any global var.
var clickAttr;
$(document).ready(function(){
clickAttr = $('form a').attr('onClick');
});
After that on Window load you can add attribute onClick
$(window).load(function(){
$('form a').attr('onClick',clickAttr);
});
I am not sure that your requirement is satisfy with this code or not, but you can try this.
Note: I am writing for A tag which is inside form without id or class, you can add a class or id to A tag.
Try after load:
var $a = $('Click Me')
$( "a:contains('Click Me')" ).replaceWith($a)
I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});