html body ondblclick get clicked element - javascript

so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?

<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}

make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>

you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}

Related

Jquery Anchor Tag Doesnt open a poup

I am trying to do 2 things:
Open a popup when someone clicks on Lease today (Please note I do not have control over the HTML, so Jquery is the only way to change the HREF)
Change the Anchor tag back to "/floor-plans.aspx" after the first click
Somehow the code is not calling the function at all and not sure how to do #2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change HREF Attribute of Anchor Tag </title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a[href^="http://"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("/floor-plans.aspx", "openPopup()"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
});
function openPopup(){
alert("popupopened");
}
</script>
</head>
<body>
<span>Lease Today</span>
</body>
</html>
There are two parts to this, the first click to do the alert, then the second to NOT do the alert but allow the click (and turn off this handler, first time only we alert)
In addition, I added a class to make the selector much simpler to use/understand.
You did not ask how to tell what was clicked in the function, so I show that as well as how to pass some extra values/objects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change HREF Attribute of Anchor Tag </title>
</head>
<body>
<span>Lease Today</span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function openPopup(event,passed) {
console.log(passed.foo.Name);
alert("popupopened was "+$(event.target).text());
}
$(function() {
$('a.replacer-clicker').on('click', function(event) {
// Get prior url if we had it
let prior = $(this).data('prior-href');
if (!prior) {
// do not go there and stop other event handlers from seeing it
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
// save old, no prior click
$(this).data('prior-href', $(this).attr("href"));
// all it with this instead so we know context of it
openPopup.apply(this, [event,{foo:{Name:"fooby"}}]);
// simple
//openPopup();
} else {
console.log(prior);
//second click (had prior)
// now turn this handler off
$(this).off('click');
// now re-trigger the click, pass some arguments
$(this).trigger('click',[{foo:{Name:"fooby"}}]);
}
});
});
</script>
</body>
</html>
Your first issue is hwo you select the anchor and the second one is related on how you use href attribute.
Fixed code:
function openPopup(){
alert("popupopened");
}
$('a[href^="/floor-plans.aspx"]').each(function(){
var oldUrl = $(this).attr("href"); // Get current url
var newUrl = oldUrl.replace("/floor-plans.aspx", "javascript:openPopup();"); // Create new url
$(this).attr("href", newUrl); // Set herf value
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>
The correct way is:
$('a[href^="/floor-plans.aspx"]').on('click', function(e) {
e.preventDefault();
alert("popupopened");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>
Instead, if the html element is not yet ready you can delegate the click event:
$(document).on('click', 'a[href^="/floor-plans.aspx"]', function(e) {
e.preventDefault();
alert("popupopened");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Lease Today</span>

Simple&Basic JS - 1st attempt to javascript (want it jQuery free)

First attempt to javascript.. not sure what I'm doing wrong...
Trying to clear the "Sample Here" when i hover mouse or focus, or click.
And Alert when the button is clicked..
I'd rather advices how I can avoid using functions inside the HTML and use them
under the to separate js/html completely!
<!DOCTYPE html>
<html>
<head>
<title>Java Script Practicing</title>
</style>
<script>
document.onreadystatechange = function ()
{
if (document.readyState == "complete")
{
//Page Loaded
function go()
{
alert("done");
}
function clear()
{
var x = document.getElementById("x").value;
x = "";
}
}
}
</script>
</head>
<body>
<form method="post">
<input onclick="clear();" type="text" id="x" value="Sample here" />
<button onclick="go();">Click !</button>
</form>
</body>
</html>
HTML5 documents don't require you state type for a <script> element if it's javascript, and you want to state which character set your document is going to use. This is pretty much always going to be utf8.
That said, you want to tap into the DOMContentLoaded event:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Java Script Practicing</title>
</head>
<body>
<form method="post">
<input class="userinput" type="text" value="Sample here" />
<button class="gobutton">Click !</button>
</form>
<script>
document.addEventListener("DOMContentLoaded", function() {
var button = document.querySelector("button.gobutton");
button.addEventListener("click", function(evt) {
console.log("button was clicked");
}):
var input = document.querySelector("input.userinput");
input.addEventListener("click", function(evt) {
input.value = "";
}):
});
</script>
</body>
</html>
If you want to call your functions from the html as you are doing, you need them to be in the global scope.
Take the definitions for the functions go() and clear() out of the onreadystatechange function. You can still use that function to call the other two, but they must be defined globally.
Also, you cannot simply change the value of the variable x and have that update the element with id=x on the page. Instead, you can use ELEMENT.setAttribute('value', '') to clear the value.
function go() {
alert("done");
}
function clear() {
var x = document.getElementById("x");
x.setAttribute('value', '');
}
document.onreadystatechange = function () {
if (document.readyState == "complete") {
go();
clear();
}
}
Mike has answered your question. Just explaining why your way didn't work. Your functions (go, clear) have become local to the onreadystatechange's callback function's scope. I.e a closure

How to exclude div from firing this event?

I use code bellow to get the text that user has double clicked:
<html>
<script language="javascript">
document.ondblclick = function() {
alert(GetSelectedText());
}
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<div id="should_trigger_event">sample of a text!</div>
<div id="should_not_trigger_event">sample of a text!</div>
</body>
</html>
I want to ondblclick event just fire up for div with id: should_trigger_event and not for div with id: should_not_trigger_event
How can we achieve that?
It is simple using jQuery :
<script language="javascript">
$(document).ready(function(){
$('#should_trigger_event').on('dblclick',function(){
alert(GetSelectedText());
});
});
function GetSelectedText() {
if (document.selection) {
return document.selection.createRange().text;
}
}
</script>
More Information on
jQuery Selectors
jQuery double click binding
Why dont you bind click event using element id:
$(function(){
$('#should_trigger_event').click(function(){
if (document.selection) {
return document.selection.createRange().text;
}});});
You can directly assign the handler to the div you want to include…
var div = document.getElementById('should_trigger_event');
div.ondblclick = function() {
alert(GetSelectedText());
}
or if you want the handler for whole document, you can check target in event object
document.ondblclick = function(e) {
if(e.target.id != 'should_not_trigger_event')
alert(GetSelectedText());
}

JavaScript focus() function doesn't focus textarea on page load

I have the following code.
<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var text = document.getElementById('text')
window.onload = function() {
text.focus()
}
window.onhashchange = function() {
text.focus()
}
}//]]>
</script>
</head>
<body>
<textarea id="text"></textarea>
<p>Click to focus</p>
</body>
</html>
Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/
Why doesn't the focus go on the textarea box when the page loads? On clicking the link, the focus does go on the textarea box, but I also want the focus to go to the textarea box on page load. Why doesn't it happen?
Note: I am aware of the HTML5 autofocus attribute for textarea. But this question is about why the above JavaScript code does not do what I intend to do.
You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. This inner onload will not be called because by the time you define it the onload event will have occurred. Try this:
window.onload=function(){
var text = document.getElementById('text')
text.focus()
window.onhashchange = function() {
text.focus()
}
}
Your demo, updated: http://jsfiddle.net/DvU63/2/
do this
<script type='text/javascript'>
window.onload=function(){
var text = document.getElementById('text')
text.focus();
window.onhashchange = function() {
text.focus();
}
}
</script>
fiddle

In a for loop how to pass parameter of function invoked by document.getElementById('').onClick

When I click on the div element I want to alert the id of div I clicked on. But on all the div elements it is alerting the last value of array i.e. 'e1'.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="populate();">
<script type="text/javascript">
function populate() {
var divArray = ["a1", "b1", "c1", "d1", "e1"];
for (var x in divArray) {
if (divArray[x] === 'a1')
document.getElementById(divArray[x]).innerHTML = "aaaaa";
else
document.getElementById(divArray[x]).innerHTML = "Common";
document.getElementById(divArray[x]).onclick = function() {
getDiv(divArray[x]);
};
}
}
function getDiv(x)
{
alert(x);
}
</script>
<div id="a1"></div>
<div id="b1"></div>
<div id="c1"></div>
<div id="d1"></div>
<div id="e1"></div>
</body>
</html>
Your x is not the x you're hoping for. This might help.
// ...
document.getElementById(divArray[x]).onclick = (function(n) {
return function() {
getDiv(divArray[n]);
};
}(x));
// ...
Replace getDiv(divArray[x]) with getDiv(this.id), as you want to return the ID of the clicked element.
This is because your for-loop has already ended by the time you actually click the div, so x is whatever it was when the loop ended.
To fix this, you need to call getDiv(this.id);
Try passing the click event (e) into your click handler
document.getElementById(divArray[x]).onclick = function(e) {
console.log(e.toElement.id);
};

Categories

Resources