click a hyperlink with javascript - href="#" - javascript

I'm new to Javascript.
I would like to click a hyperlink with Javascript.
the html looks like this:
<a id="random563e035c2b9149" class="btn" href="#">Launch PDF editor...</a>
the id changes every time I refresh the page, so I can't use it.
how do I click this hyperlink with javascript?
( if it helps, this is the div this hyperlink is in:
<div class="visibleifjs" id="yui_3_17_2_2_1446906385088_829"><a id="random563e0a0eede6f9" class="btn" href="#">Launch PDF editor...</a><div class="assignfeedback_editpdf_unsavedchanges warning">Unsaved changes</div></div>
)
enter code here

the id changes every time I refresh the page, so I can't use it.
id appear to begin with string "random" ? , followed by random integers ?
Try selecting a having id beginning with "random" , having class btn ; calling .click() on DOM element
$("a[id^=random][class=btn]")[0].click()

you can use class asigned to it:
$(".btn").on("click",function(){
alert($(this).html());
});

If the id of the parent div stays the same.
$('#yui_3_17_2_2_1446906385088_829 a').click(function(){
//do something
});

I have a solution but it's ugly... hope someone has a better idea.
luckily there are only three buttons ('btn' class) on this page, so the button I want to push was easy to find (but in other cases, if there are a million button on this page it wouldn't be so easy to find the right one...)
in my case, my button is the first button, so this works:
document.getElementsByClassName('btn')[0].click();

Related

checking if the user clicked on href after a JQuery modify

I am trying to check if a user clicked on a kind of a href in a specific class.
I am appending the class in jquery because I need to put a different link every time
$("#list-dir").append("<a href='' class='add-href'><il class='dir-items'> " + dir_items[i] + " <br> </il></a>")
$(".add-href").eq(i).attr("href", href_element);
and it works as it should I can see the class and the correct link in the HTML file. But when I try to check if the user clicks it nothing works for some reason like the class isn't there
This ^ was how the webpage looks after I modified it with JQuery.
I already tried putting this code:
$(document).ready(function(){
$(".add-href").on("click", function(e){
console.log("d")
});
});
as most of the answers suggest but it didn't work.
Thanks to CBore for giving me the answer. I had to use event delegation. after I did it worked perfectly fine. in addition like Aslan Kayardi said I could of also create another element like the data-href and enter the link in the value

Making a button a clickable link (With a twist)

So I have a snippet that I'm using to build some buttons.
<font color=white><button class="button"><span>Register</span></button></font>
<button class="button" onclick="window.location='http://www.google.com';"><span>SP Training</span></button>
<button class="button"><span>Assistance</span></button>
<button class="button"><span>Orders</span></button>
<button class="button"><span>KM Milsuite</span></button>
<button class="button"><span>TMT</span></button>
As you can see I have tried wrapping the whole thing in href, I have tried wrapping the span in href, I have tried wrapping just the font in href, all failed
Ok so I trekked down the java world and tried some on click (numerous variations I have found on this site) none of which work! Every button is a clickable but EVERY button simply links back to the page i'm currently working on. By no means am I an expert at all this but I expected a little give on this!
Any suggestions?
The purpose of a button is to either:
Submit a form (type="submit", the default)
Allow JavaScript to be triggered (type="button")
As you can see I have tried wrapping the whole thing in href
The HTML specification forbids that.
I have tried wrapping the span in href
The span appears to serve no purpose
Every button is a clickable but EVERY button simply links back to the page i'm currently working on
If clicking the button is reloading the current page, then it is probably a submit button inside a form with an action attribute that resolves to the current page (or no action attribute).
If you want a link then use a link and do not use a button.
If you want your link to look like a button, then use CSS to style it that way. Note that the :active pseudo-class is useful for achieving the 3d depressed effect when the link is clicked.
The span tag inside your button is catching the click action. You must take the span out of the "bubbling" chain.
The easiest way is to apply CSS and add the class to your span tags.
span.nonclickable {
pointer-events: none;
}
After that you can catch the button clicks.
A more detailed explanation can be found here: Use CSS to make a span not clickable
It is not quite clear what you want these buttons to do. Use a-tags to link to other pages and use buttons to refer to an action in javascript or a form submit.
You could try this :
<input type="button" onclick="myF()" />
<script>
function myF() {
window.open('http://www.google.com', '_blank', 'resizable=yes');
}
</script>
Hope it helps

not changing color when clicking button

i am using bootstrap to change the button color when clicked, but i think i am doing something wrong and the button is not changing it's color when i am clicking the button.
this is my button code -
<td>
<a class="mylink" href="#"><button class="btn btn-default btn-xs">{% trans %}Allow{% endtrans %}</button></a>
</td>
this is my javascript code ---
<script type="text/javascript">
$(document).ready(function() {
if (localStorage.getItem('isCliked'){
$("#mylink").addClass('btn-success');
$("#mylink").removeClass('btn-default');
}
$('#mylink').on('click', function() {
$(this).addClass('btn-success');
$(this).removeClass('btn-default');
// set the value upon clicking
localStorage.setItem('isCliked', true)
});
i need to change the button color when clicked and when the page is called again it should check whether it is activated or not.
Can anyone help me to solve this problem.
Probably the problem is here.
$("#mylink")
This selects the element with the id="mylink" and not the element with the class="mylink"
If you want to select a class, go for this.
$(".mylink")
CSS Selectors: w3schools
First of all, mylink is a class in your code.
<a href="#" class="mylink">
But in jQuery you're using an ID ($("#mylink")). Also, <a> is an ascendent of <button>. So correct your every bit of $("#mylink") to:
$(".mylink button")
That way you'll be targeting the <button> tag inside your <a> tag with class .mylink.
Reference: http://www.w3schools.com/jquery/jquery_ref_selectors.asp
With $('#someID') you are selecting something by it's id. But you use classes ("myLink") so you should use $(".myLink").
And despite that you make it more complicated than it needs to be. Maybe you want to try to do it just with css.
Here is an example which is very similar to your question:
Pressed <button> CSS
There are some errors in your code:
It is jQuery, not JavaScript (it's a little bit different)
You are changing the <a> class "myLink" NOT the <button> class
You are referring to a class (".myClassName") as a id ("#myIdName")
Others things (i.e. how javascript handle the DOM element)... you should read and study a little bit more.
Anyway, I've made you a working fiddle.

Current menu item

I've been trying every single tutorial I found online and none seems to work for me.
I've got these buttons:
<a href='faq.php'><div class='button'>
<div class='button_top'>
</div>
<div class='button_bot'>
FAQ
</div></a>
http://jsfiddle.net/6G8bk/
and I'd like that the top of the button would stay highlighted if the page url is same as href of the button.
Ty for any answers in advance!
Here's the fixed jsfiddle with jquery I tried but still won't work: http://jsfiddle.net/6G8bk/4/
A few things:
In your jQuery, you're trying to select all <a> elements that have a parent class of button, and according to your HTML you do not have (the button class is a child of the <a> element).
The page's URL won't work in JSFiddle because it will get the JSFiddle link, which will be different from the one on your website.
Since you want button_top to be visible on hover, you'll need to use JavaScript. As fas as I know, you can't manipulate another element on hover with pure CSS.
Here is a working Fiddle of what I think you want. I've left comments in the code that might help you.
http://jsfiddle.net/6G8bk/6/
You can retrieve the current url page by using $_SERVER["SCRIPT_NAME"] and comparing it to each element of the menu.
If it match, you put another class in the menu element with CSS rules to have the layout you want.

What does href expression do?

I have seen the following href used in webpages from time to time. However, I don't understand what this is trying to do or the technique. Can someone elaborate please?
An <a> element is invalid HTML unless it has either an href or name attribute.
If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.
Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.
He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.
Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).
There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.
basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)
<script>
function doSomething() {
alert("hello")
}
</script>
click me
clicking the link will fire the alert.
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Avoids the "moving to the top" effect of the empty href="#"
Avoids the use of javascript
Drawbacks:
You must be sure the anchor name is not used in the document.
The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.
Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.
is just shorthand for:
It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.
Interesting fact
I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).
It is a way of running Javascript instead of following a link:
link
When there isn't actually javascript to run (like your example) it does nothing.
Refer to this:
Link to the website opened in different tab
Link to the div in the page(look at the chaneged url)
Nothing happens if there is no javaScript to render
javascript: tells the browser going to write javascript code
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id) works as onClick but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
Since it is a styling issue, instead of polluting the HTML with non valid syntax, you could/should use a W3 valid workaround:
Format the HTML properly, without href, following the W3 accessibility guide lines for buttons.
Use CSS to fix the initial goal of applying a clickable UX effect on a control.
Here's a live example for you to try the UX.
HTML
<a role="button" aria-pressed="false">Underlined + Pointer</a>
<a role="button" aria-pressed="false" class="btn">Pointer</a>
CSS
a[role="button"]:not([href]):not(.btn) { text-decoration: underline; }
a[role="button"]:not([href]) { cursor: pointer; }
I was searching for a solution that does not refresh pages but opens menu items on Ipads and phones.
I tried it on also mobile, It works well
Dr
1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows
<div class="table-cell">
<span id="clearRow{id}">
Clear
</span>
</div>
<div class="table-cell">
<span id="deleteRow{id}">
Delete
</span>
</div>
//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
});
//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
//depending upon levels of parent / child use 1 to many .parent().parent().parent()
$(this).parent().remove();
});

Categories