Graceful upgrading of an anchor element - javascript

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;'>

Related

New window size

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>

stopPropagation() not working

I want to stop bubbling when click on image. I cannot set javascript void on href as it is required. I have used stopPropagation but it is not working.
function showurl(e){
e.stopPropagation()
window.location="http://www.yahoo.co.in"
}
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" onclick="showurl(event)" />
</a>
As this was a jQuery question I would suggest never using onclick attributes. They only support a single handler and they are are "ugly" (read: harder to find and maintain) :)
$('img").onclick = function(e) {
e.preventDefault();
window.location="http://www.yahoo.co.in";
}
or
$('img").onclick = function() {
window.location="http://www.yahoo.co.in";
// return false here does the same as e.stopPropagation() and e.preventDefault();
return false;
}
As this handler applies to all img elements, you may want to data-drive the whole thing (using attributes) like this:
Put the target url in the image as a data-url attribute
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png"
data-url="http://www.yahoo.co.in" />
</a>
And code-wise:
$('img").onclick = function(e) {
// See if image has a data-url attribute
var url = $(this).data('url');
if (url){
window.location=url;
// only prevent default if it was an image with a link attribute
e.preventDefault();
}
}
I would suggest binding it from JS, even with a basic onclick then use return false; or use preventDefault. (demo)
document.getElementsByTagName("img")[0].onclick = function() {
window.location="http://www.yahoo.co.in";
return false;
}
HTML
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" />
</a>

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');">

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.

How can i dynamically Change onmouseover, onmouseout and onClick WITH parameters?

I have an image:
<img id="reqPic" src="mark.png" />
I also have declared a flag earlier on in the page:
<script type="text/javascript">
var isToolTipEnabled = true;
</script>
I now want to be able to check the flag and if its true, assign the onmouseover and onmouseout events. However, the onmousover event has to be changed to another function called Tip('string') which takes in a string. I have seen other questions on here on how to change this but it I dont see how I can pass paramters to the new function I want to change to.
The onClick would be changed to something like this:
onClick="javascript:toggleHelp('reftypeHelp');";
Any help on this would be greatly appreciated.
Thanks!
document.getElementById("reqPic").onmouseover = function() { Tip('This is the string.'); };
You could have an onload event on your body tag which calls a function that checks necessary values.
<script type="text/javascript">
var isToolTipEnabled = true;
function eventAdder() {
if (isToolTipEnabled) {
var img = document.getElementById('reqPic');
img.onmouseover = function() {
Tip('string');
}
img.onmouseout = whateverElse;
}
}
</script>
<body onload="eventAdder();">
with jQuery you could use the hover function but yeah creating an inline function works too

Categories

Resources