when location path is empty use onClick function - javascript

I'm trying to use a href and onClick depending on the url.
if $location.path() is empty such like www.mysite.com/ then use onClick function
if url is like www.mysite.com/about then use href="javascript:history.back()"
<a href="javascript:history.back()" data-ng-click="vm.backToResult();">
<i class="fa fa-angle-left"></i>
Back to Search Results
</a>
vm.backToResult = function() {
if (!$location.path()) {
$window.history.back();
} else {
$window.location.href = '#!/list-of/options/';
}
}
I think this is working but I have to double click to actually trigger it but not entirely sure to be honest.

Related

disable href link if javscript call return false

I have following code, but it doesnt work
<a href="Order-addCopy?id=15658">
<img src="img/add.png" onclick="copyOrderPopupMsg()">
</a>
function copyOrderPopupMsg() {
if (confirm("open the following link?")) {
return true;
} else {
return false;
}
}
How can I disable the href link if the user click "cancel" on the popup window?
To cancel navigation using that style of code you have to return from the onclick function.
You are returning from copyOrderPopupMsg but you don't do anything with the result.
You also have to handle the event on the link not the image inside the link.
Note, also that confirm returns a boolean, so wrapping it in an if that generates a boolean is pointless.
A link with no text content is also highly inaccessible, don't forget the alt attribute
function copyOrderPopupMsg() {
return confirm("open the following link?")
}
<a href="Order-addCopy?id=15658" onclick="return copyOrderPopupMsg()">
<img src="img/add.png" alt="Add">
</a>
Modern code also avoids onclick attributes as they have numerous issues (including lack of separation of concerns and weird scoping issues) so I recommend using addEventListener and making use of the event object.
function copyOrderPopupMsg(event) {
if (!confirm("open the following link?")) event.preventDefault();
}
document.querySelector('a').addEventListener('click', copyOrderPopupMsg);
<a href="Order-addCopy?id=15658">
<img src="img/add.png" alt="Add">
</a>
I simple solution
<a href="Order-addCopy?id=15658">
<img src="img/add.png" onclick="return copyOrderPopupMsg()">
</a>
Just add the return in onclick.
You need to remove the link completely.
<img src="img/add.png" onclick="copyOrderPopupMsg()" data-href="Order-addCopy?id=15658">
function copyOrderPopupMsg(event) {
if (confirm("open the following link?")) {
window.location = event.target.dataset.href;
}
}
Make sure you have a full URL. The current one is not valid for this operation.
If you want to use a relative path, you can create a hidden link and click it by function.
<a class="hidden click-when-confirmed" href="Order-addCopy?id=15658"></a>
function copyOrderPopupMsg(event) {
if (confirm("open the following link?")) {
document.quertSelector('.click-when-confirmed').click();
}
}
I think preventDefault would be the best in your case:
function onclickA(e) {
if (!confirm('open the following link?')) {
e.preventDefault();
}
}
<a href="Order-addCopy?id=15658" onclick="onclickA(event)">
<img src="https://upload.wikimedia.org/wikipedia/commons/5/50/Yes_Check_Circle.svg" />
</a>
try this: remove anchor tag and change to this
function copyOrderPopupMsg() {
if (confirm("open the following link?")) {
document.location.href="Order-addCopy?id=15658";
} else {
return false;
}
}

How to pass a value from <a> (anchor tag) to a function in react js?

I am trying to create a CRUD application using react and mvc .net. On clicking the edit/delete link in the table, I want the corresponding EmpID to be passed to a function and then it should be passed to a controller, where edit/delete operation happens. Please let me know how to do this.
var EmployeeRow = React.createClass({
Editnavigate: function(){
},
Deletenavigate: function(){
},
render: function () {
return (
<tr>
<td>{this.props.item.EmployeeID}</td>
<td>{this.props.item.FirstName}</td>
<td>{this.props.item.LastName}</td>
<td>
<a href="#" data-value="this.props.item.EmployeeID" onclick=this.Editnavigate>edit</a> |
<a href="#" data-value="this.props.item.EmployeeID" onclick=this.Deletenavigate>delete</a>
</td>
</tr>
);
}
});
You can do it by using onClick, as simple as this
Editnavigate (e,id) {
e.preventDefault();
alert(id);
}
<a href="#" onClick={(e) => this.Editnavigate(e,1)}>edit</a> // pass your id inplace of 1
WORKING DEMO
Note : You can also pass via data-value , but still that's not good
idea, in that case you still need to access dom and fetch via that
field, instead that just pass the value when its possible. That will
be simple and requires less processing.
You could retrieve the data you want from your click handlers like this:
EditNavigable: function(e) {
var clickedLink = e.currentTarget;
var data = clickedLink.getAttribute('data-value');
}
Or you could put it into it's own function like so:
getDataValue: function(e) {
return e.currentTarget.getAttribute('data-value');
}
and then call it from your edit and delete functions like this:
EditNavigable: function(e) {
var data = this.getDataValue(e);
}
You can do it as below. I was trying the same in reactjs with javascript(ES-6), but nothing else worked except for below-
<a href = 'www.google.com' onClick={clickHandler} > Google </a>
clickHandler(event){
event.preventDefault();
alert("This is alert: " + event.target.getAttribute('href'));
}
Here event.target.getAttribute('href') will return 'www.google.com'

jQuery addClass() not working when also using attr("href", something)

I want to create a link (in form of a Bootstrap button) that works only on the second click; on the first click it is supposed to change its appearance a bit. For this I use .addClass(newClass), .removeClass(oldClass), and then attr("href", newUrl).
(Edit) To clarify: In the beginning, the link (anchor) has "#" as its href target, and an onlick handler. That handler, when executed on the first click, will remove itself from the anchor, and instead set the desired target URL in the hrefattribute. That is supposed to cause the link to only redirect to its target URL on the second click.)
This almost works, but only if I omit the attr() setting. When it is there, the class reverts to the old class of the link as soon as the script exits. When I step through it in the debugger, the link briefly changes its appearance as expected, but changes back when the event handler exits.
This is the HTML code:
<a id="twoclick-vjffkrzw" onclick="enabletwoclickbutton('twoclick-vjffkrzw',
'http://localhost/something.php?cmd=admin&func=userdetail&pk=53&action=removerole&rolepk=1')"
class="btn btn-xs btn-warning" href="#">Remove this</a>
The script:
function enabletwoclickbutton(btn_id, url) {
var whichbtn = '#' + btn_id;
var btn = $(whichbtn);
if (btn.hasClass("btn-warning")) {
btn.off("click");
btn.attr("href", url);
btn.removeClass('btn-warning');
btn.addClass('btn-danger');
} else {
console.log("Hey, this shouldnt happen.");
}
}
I'm not very experienced in JS and jQuery, so it's quite possible that this is a stupid mistake on my side, but I just can't see it.
Use e.preventDefault() to avoid the default behavior of anchor.
Your way (however I recommend you to go with one below for readability and easy to modify later.)
html
<a id="twoclick-vjffkrzw" onclick="enabletwoclickbutton(event,'twoclick-vjffkrzw', 'http://localhost/something.php?cmd=admin&func=userdetail&pk=53&action=removerole&rolepk=1')" class="btn btn-xs btn-warning" href="#">Remove this</a>
js
function enabletwoclickbutton(e,btn_id, url) {
var whichbtn = '#' + btn_id;
var btn = $(whichbtn);
if (btn.hasClass("btn-warning")) {
e.preventDefault();
//btn.off("click");
btn.attr("href", url);
btn.removeClass('btn-warning')
.addClass('btn-danger');
} else {
console.log("Hey, this shouldnt happen.");
}
}
Recommended
Do not mix your javascript and html which is very hard to read as you can see in your code. You can write the entire code in javascript only
eg.
$('#twoclick-vjffkrzw').click(function(e){
var btn = $(this);
if (btn.hasClass("btn-warning")) {
e.preventDefault();
//btn.off("click");
btn.attr("href", 'http://localhost/something.php?cmd=admin&func=userdetail&pk=53&action=removerole&rolepk=1');
btn.removeClass('btn-warning');
btn.addClass('btn-danger');
} else {
console.log("Hey, this shouldnt happen.");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="twoclick-vjffkrzw" class="btn btn-xs btn-warning" href="#">Remove this</a>
First add return false; after the onclick function call to stop the default redirect. Then in your function you can set the onclick to null so that it isn't called a second time.
function enabletwoclickbutton(btn_id, url) {
var whichbtn = '#' + btn_id;
var btn = $(whichbtn);
if (btn.hasClass("btn-warning")) {
btn.off("click");
btn.attr("href", url);
btn.removeClass('btn-warning');
btn.addClass('btn-danger');
btn.attr('onclick', null);
} else {
console.log("Hey, this shouldnt happen.");
}
}
.btn-warning {
color: orange;
}
.btn-danger {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="twoclick-vjffkrzw" onclick="enabletwoclickbutton('twoclick-vjffkrzw',
'http://localhost/something.php?cmd=admin&func=userdetail&pk=53&action=removerole&rolepk=1');return false;" class="btn btn-xs btn-warning" href="#">Remove this</a>
you have to check if it is the first time you click the button. to do this you can use a variable . check the code below
var clk=0;
function enabletwoclickbutton(btn_id, url) {
if(clk==0){
clk++;
}else{
clk=0;
var whichbtn = '#' + btn_id;
var btn = $(whichbtn);
if (btn.hasClass("btn-warning")) {
btn.off("click");
btn.attr("href", url);
btn.removeClass('btn-warning');
btn.addClass('btn-danger');
} else {
console.log("Hey, this shouldnt happen.");
}
}
check jsfiddle
I'd use data attribute to store url value (added my-btn class for clarity)
<a data-action="http://localhost/something.php?cmd=admin&func=userdetail&pk=53&action=removerole&rolepk=1" class="btn btn-xs btn-warning my-btn" href="#">Remove this</a>
Then set click function with jQuery instead of using onClick attribute (as it's not good practice):
$('.my-btn').click(function(event){
// prevent default click action:
event.preventDefault();
if ($(this).hasClass("btn-warning")) {
$(this).removeClass('btn-warning').addClass('btn-danger');
}else{
// go to url on a second click:
location.href = $(this).data("action");
}
});
EDIT (#A.Wolff comment)
BTW.: Checking the existence of btn-warning class is actually pointless. The click event won't be handled at the second click anyway...
$('.my-btn').click(function(event){
event.preventDefault();
$(this).removeClass('btn-warning').addClass('btn-danger')
.off('click').attr('href', $(this).data("action"));
});
With input from the various answers, I was able to find out what was happening.
Apparently the changed href will be executed only after the the event handler exits. Since in my configuration by chnce it redirected to the same page, the page was actually reloaded, that's why the button/link got its original appearance back and that tricked me into believing that the attr() setting didn't work right.
The key was to simply call event.preventDefault() before setting the new URL.
Some of you recommended (directly or indirectly) to generate the button click handler in JS directly. I don't think this would make the code better readable (the only thing that made the HTML unreadable is the long URL.) As the HTML is generated dynamically, this wouldn't be a practical solution anyway.
So, the finalized code looks like this:
function enabletwoclickbutton(e, btn_id, url) {
var whichbtn = '#' + btn_id;
var btn = $(whichbtn);
if (btn.hasClass("btn-warning")) {
e.preventDefault();
btn.off("click");
btn.attr("href", url);
btn.removeClass('btn-warning');
btn.addClass('btn-danger');
} else {
console.log("Hey, this shouldnt happen.");
}
}
Now it works as exected.

jQuery .click() doesn't fire but console.log shows output

I'm having a problem in my code where I click a DOM-element using JavaScript. The click does not work and I am almost sure it is no dumb programming mistake (always dangerous to say).
After deleting some DOM-elements I want my code to click an element and trigger its onclick event. However this doesn't work. According to my code the event triggers but the event doesn't happen and the click event returns the jQuery object.
HTML:
<div class="castor-tabs">
<div class="castor-tab" data-path="../SiteBuilding/alertbox.js" data-saved="saved" data-editor="5475c897f1900editor">
<span class="castor-filename">alertbox.js</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab" data-path="../SiteBuilding/index.php" data-saved="saved" data-editor="5475c89903e70editor">
<span class="castor-filename">index.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
<div class="castor-tab active" data-path="../SiteBuilding/makesite.php" data-saved="saved" data-editor="5475c8997ac77editor">
<span class="castor-filename">makesite.php</span>
<span class="castor-close"><i class="fa fa-fw fa-times"></i></span>
</div>
</div>
JavaScript:
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
});
The onclick event:
$(".castor-tabs").on("click", ".castor-tab", function() {
$(".castor-tab.active").removeClass("active");
$(this).addClass("active");
var editor = $(this).attr("data-editor");
$(".CodeMirror").hide();
$("#" + editor).show();
});
I saved the element in the window object for a reason. After the code runs and it skips the click-part I still have the DOM-element i want to click saved in the window object. This means I can run
console.log(window.newTab.click());
again. Surprisingly this does click the element and this does activate the click-event. It also returns the DOM-element instead of the jQuery-object.
The image shows in the first two lines the failed click. The third line is my manual input and the fourth line is the successful return value of the click().
I hope you can help me to solve this.
UPDATE
.trigger("click") unfortunately gives the same output..
UPDATE 2
To help you i made the website available on a subdomain. I know many of you hate it if you have to go to a different page but I hope you'll forgive me because in my opinion this cant be solved through JSFiddle.
The link is http://castor.marknijboer.nl.
After clicking some pages to open try closing them and you'll see what i mean.
try adding return false; at the end, when binding .castor-close click event
$(".castor-tabs").on("click", ".castor-close", function() {
var tab = $(this).parent();
if(tab.attr("data-saved") == "saved") {
// File is saved
if($(".castor-tab").length > 1) {
// 1 element is 'tab' the other is a second tab
if(tab.next().length > 0) {
// If element is to the right
window.newTab = tab.next();
} else if(tab.prev().length > 0) {
// If element is to the left
window.newTab = tab.prev();
}
} else {
window.newTab = false;
}
var editor = tab.attr("data-editor");
$("#" + editor).remove(); // textarea linked to CodeMirror
$("#" + editor + "editor").remove(); // Huge CodeMirror-element
tab.remove();
if(window.newTab) {
console.log("window.newTab.click()");
console.log(window.newTab.click()); // Simulate click()
}
} else {
// File isn't saved
}
return false;
});
Instead of simulating a click, why not just pull the click logic out of your click function and just call the javascript function using the arguments that you'll need to perform your business logic?
Your code is working but not able to trigger click event binded to castor-close because i tag is empty. Put some text in it and check
<span class="castor-close"><i class="fa fa-fw fa-times">Click me</i></span>
DEMO
Your click handler has the requirement that the click target should have the class castor-close but when you are calling click via JavaScript you are clicking the parent element instead (.castor-tab), and the click handler doesn't react.

javascript toggle visibility and add function preventDefault

i´m trying to display popup-divs within a site and it works quite well, except for one thing –
i want to prevent the Default behavior of refreshing the site. I´m new to javascript and i honestly don´t know how to add the function (i already found the right one, i think...).
<script type="text/javascript">
function toggleVisibility(selectedPopup) {
var popvar = document.getElementsByClassName('popup');
for(var i=0; i<popvar.length; i++) {
if(popvar[i].id == selectedPopup) {
popvar[i].style.visibility = 'visible';
} else {
popvar[i].style.visibility = 'hidden';
}
}
}
It works like i wanted it to work – it displays the selected DIV, hides the other and vice versa.
Still, i want to prevent the site from jumping to the top. So i added this snippet:
$(function() {
$("#").click(function(event){
event.preventDefault()
});
});
The responding html is this:
<a href="#" onclick="toggleVisibility('pop01');">
and this
<div id="pop01" class="popup">
<img src="assets/img/01/01_02_pop_01.png"></img>
</div>
How can i include the second javascript snippet into the first one?
Many thanks in advance...
You should just be able to pass event into your function.
The HTML
<a href="#" onclick="toggleVisibility(event, 'pop01');">
The Javascript (partial)
function toggleVisibility(event, selectedPopup) {
event.preventDefault();
var popvar = document.getElementsByClassName('popup');
// etc...
}
I believe that should do it!
JSFiddle Example: http://jsfiddle.net/c4LXf/
As an alternative you can just remove the # and replace with javascript:;
<a href="javascript:;" onclick="toggleVisibility('pop01');">
Or remove the onclick and just use the href:
<a href="javascript:toggleVisibility('pop01');">
Instead of
$(function() {
$("#").click(function(event){
event.preventDefault()
});
try
$(function() {
$("#").click(function(event){
return false;
});
You can just use following:
<a href="#" onclick="return toggleVisibility('pop01');">
If you add a return false in your function:
function toggleVisibility(selectedPopup) {
// your code ...
return false;
}
Or, Change your link like:
<a href="javascript:toggleVisibility('pop01');">

Categories

Resources