New window size - javascript

I know that this question is been asked tons of times, but I'm asking not exactly that. This code belongs to website menu bar, so I have to keep this code, otherwise design would be totally different.
Code:
<li class="removable-parent">
<a class="removable-parent" href="http://88.88.209.56:12/player.html" data-
link-type="EXTERNAL" target= "_blank">
<span id="4884dd90" class="preview-element Link item-link magic-circle-
holder text-element custom" data-menu-name="PREVIEW_LINK" >Spiller</span>
</a>
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
} document.getElementById("http://88.88.209.56:12/player.html").onclick=clickHandler
}
</script>
</li>
So how can I make that this code opens window in decided size?

You will need to use javascript.
Get a reference to your object and handle the click event. In that event, use window.open with the proper parameters to set the width and height of your pop-up window.
Make sure you cancel the original event so you don't end up with two pop-ups.
Something like:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
var elems = document.querySelectorAll(".removable-parent");
for (var i = 0, elem; elem = elems[i]; ++i) {
elem.onclick = clickHandler;
}
</script>
Or, if you wish to apply this behavior on one link, first add an id attribute to your link:
<a class="removable-parent" id="myelement" href="http://88.88.209.56:12/player.html" data-link-type="EXTERNAL" target= "_blank">
The script should then be simplified so it applies only on that element:
<script>
function clickHandler() {
window.open(this.href, "_blank", "width=640,height=480");
return false; // to prevent default action.
}
document.getElementById("myelement").onclick = clickHandler;
</script>

Related

Prevent anchor click after one click

I am facing one issue, I want to disable anchor click after one click. I have
on-click attribute set in my anchor tag. Below is my HTML
<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>
After I click "Verify" I am changing anchors text to "Verifying..." and one more thing I am trying to disable this anchor to avoid click in between the verification logic going on.
I have tried event.preventdefault() and also added disabled attribute to anchor.
But nothing works.
Please help!
If you were using jQuery for this you could have done this more easly.
Here we add a new class to a link to show that it has been clicked already. We check this when a click is made.
<a style="cursor:pointer;" id="someId">Verify</a>
$('#someId').on('click',function(){
//Check if button has class 'disabled' and then do your function.
if(! $(this).hasClass('disabled')){
$(this).addClass('disabled');
Myfuntion();
$(this).removeClass('disabled');
}
});
Here is a demo as to how it could be done using Javascript.
//Pass the event target to the function
function Myfuntion(elem) {
//If the element has no "data-status" attribute
if (!elem.getAttribute("data-status")) {
//Set attribute "data-status=progress"
elem.setAttribute("data-status", "progress");
//Change the text of the element
elem.textContent = "Verifying...";
//The setTimeout(s) below is only for the demp purpose
//Lets say, your verification process takes 4 seconds
//When complte
setTimeout(function() {
//Remove the attribute "data-status"
elem.removeAttribute("data-status");
//Notify the use that verification is done
elem.textContent = "Verified";
//Again, this is only for demo purpose
setTimeout(function() {
//User may verify again
elem.textContent = "Verify";
}, 1000);
}, 4000);
}
return false;
}
Link to the demo
There are plenty of ways to do this; one simple approach is to just redefine the function itself:
var myFunction = function() {
alert('clicked');
// do whatever your function needs to do on first click, then:
myFunction = function() { // redefine it
// to no-op, or to another action
alert('second click');
}
}
<a onclick="myFunction()">click me</a>

Override javascript click event one time

I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
​
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});
​

How to display a confirmation dialog when clicking an <a> link?

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.
Link
If the user clicks “Yes”, the link should load, if “No” nothing will happen.
I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?
Inline event handler
In the most simple way, you can use the confirm() function in an inline onclick handler.
Link
Advanced event handling
But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.
Link
...
<script type="text/javascript">
var elems = document.getElementsByClassName('confirmation');
var confirmIt = function (e) {
if (!confirm('Are you sure?')) e.preventDefault();
};
for (var i = 0, l = elems.length; i < l; i++) {
elems[i].addEventListener('click', confirmIt, false);
}
</script>
This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.
jQuery
I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:
Link
...
<!-- Include jQuery - see http://jquery.com -->
<script type="text/javascript">
$('.confirmation').on('click', function () {
return confirm('Are you sure?');
});
</script>
You can also try this:
<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
Link Text
</a>
I'd suggest avoiding in-line JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
var check = confirm("Are you sure you want to leave?");
if (check == true) {
return true;
}
else {
return false;
}
};
}​
JS Fiddle demo.
The above updated to reduce space, though maintaining clarity/function:
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].onclick = function() {
return confirm("Are you sure you want to leave?");
};
}
JS Fiddle demo.
A somewhat belated update, to use addEventListener() (as suggested, by bažmegakapa, in the comments below):
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
var aElems = document.getElementsByTagName('a');
for (var i = 0, len = aElems.length; i < len; i++) {
aElems[i].addEventListener('click', reallySure);
}
JS Fiddle demo.
The above binds a function to the event of each individual link; which is potentially quite wasteful, when you could bind the event-handling (using delegation) to an ancestor element, such as the following:
function reallySure (event) {
var message = 'Are you sure about that?';
action = confirm(message) ? true : event.preventDefault();
}
function actionToFunction (event) {
switch (event.target.tagName.toLowerCase()) {
case 'a' :
reallySure(event);
break;
default:
break;
}
}
document.body.addEventListener('click', actionToFunction);
JS Fiddle demo.
Because the event-handling is attached to the body element, which normally contains a host of other, clickable, elements I've used an interim function (actionToFunction) to determine what to do with that click. If the clicked element is a link, and therefore has a tagName of a, the click-handling is passed to the reallySure() function.
References:
addEventListener().
Conditional ('ternary') operator.
confirm().
getElementsByTagName().
onclick.
if () {}.
Confirm OK, then goto URL (uses onclick())
jAplus
You can do it, without writing JavaScript code
<head>
<script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
Link
...
</body>
Demo page
This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).
function myClickHandler(evt) {
var allowLink = confirm('Continue with link?');
if (!allowLink) {
evt.returnValue = false; //for older Internet Explorer
if (evt.preventDefault) {
evt.preventDefault();
}
return false;
}
}
You can attach this handler with either:
document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);
Or for older versions of internet explorer:
document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
USING PHP, HTML AND JAVASCRIPT for prompting
Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.
<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>
the reason i used php code in the middle is because i cant use it from the beginning..
the code below doesnt work for me:-
echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";
and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.
Most browsers don't display the custom message passed to confirm().
With this method, you can show a popup with a custom message if your user changed the value of any <input> field.
You can apply this only to some links, or even other HTML elements in your page. Just add a custom class to all the links that need confirmation and apply use the following code:
$(document).ready(function() {
let unsaved = false;
// detect changes in all input fields and set the 'unsaved' flag
$(":input").change(() => unsaved = true);
// trigger popup on click
$('.dangerous-link').click(function() {
if (unsaved && !window.confirm("Are you sure you want to nuke the world?")) {
return; // user didn't confirm
}
// either there are no unsaved changes or the user confirmed
window.location.href = $(this).data('destination');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="Nuclear code here" />
<a data-destination="https://en.wikipedia.org/wiki/Boom" class="dangerous-link">
Launch nuke!
</a>
Try changing the input value in the example to get a preview of how it works.

Modify target url in onclick handler

Is it possible to modify the target URL in the onclick handler? How?
I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.
$(...).click(function () {
if (check_some_condition)
// modify target url here...
// do not want to do window.location= - this is not clean
// as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
return true;
});
Try
​$(function(){
$("#theLink").click(function(){
$(this).attr("href","http://tnbelt.com");
});
});​​​​
Edit: Updated code because the event handler script is executed first and then the default action takes place.
Added below version to show you that you can use .click as you didn't notice the quirks mode link I shared with you. DEMO
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Commented e.preventDefault(); & $(this).click() as it is not required..
DEMO
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
//e.preventDefault();
this.href = "http://www.google.com";
//$(this).click();
});
});
Let us consider a hidden anchor tag
<a id="linkId" href="myPageToGo.html" class="thickbox" title="" style="visibility:hidden;">Link</a>
Then you can simulate the anchor click in your code...
$(...).click(function () {
if (check_some_condition)
$('#linkId').click();
return true;
});
EDIT - Alternative way
Wrap the element clicked inside a anchor tag...
$(...).click(function () {
if (check_some_condition)
$(this).wrap('<a id="new1" />');
$('#new1').click();
return true;
});
Yup.
$(this).attr('href', 'http://example.com/');
A lot of the answers including the top comment have missed out on an important point. If a user simply right clicks the URL to perhaps open in a new tab/window, this method won't work because you're directly requesting at the location specified by the 'href' URL instead of going through the onclick event.
You could try the same at this demo fiddle mentioned on Gourneau's post.
http://jsfiddle.net/skram/PtNfD/7/
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
this.href = "http://www.google.com";
});
});

Graceful upgrading of an anchor element

I want to add a JavaScript functionality to an array of thumbnails such that the image would expand upon clicking instead of opening in the current window. I am thinking of having a function within the onclick attribute, but I don't think this work:
<script type='text/javascript'>
function expand(){
this.height = 200;
this.width = 200;
}
</script>
<a href='/image_1.jpg' onclick='expand()'>
<img src='/image_1.jpg'>
</a>
If JavaScript is not enabled, I would like the link to work. Any idea how to go about doing this? Thanks for your time :)
You have to give this as a variable in the function for example ths
<script type='text/javascript'>
function expand(ths){
$(ths).find('img').height('200');
$(ths).find('img').width('200');
return false;
}
</script>
<a href='/image_1.jpg' onclick='expand(this)'>
<img src='/image_1.jpg'>
</a>
And return false says Prusse.
** UPDATED **
If you want to resize image, you must call the image and no link.
Don't use the onclick handler:
Instead:
var elem = document.getElementById("the-id-of-a");
elem.addEventListener('click', function(e) { /* handle event */ e.preventDefault(); return false; });
See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Just make the onclick handler return false. Using inline handlers like in your example:
<a href='/image_1.jpg' onclick='expand(); return false;'>

Categories

Resources