Is there something like a clicked===true conditional statment in javascript? - javascript

using javascript, is there a condition something like this
if (clicked===true && var===3) {
function executes here
}
if there isn't, how can you get the same effect?

For mouse and UI handling the Javascript model is based on events. In other words what you do is
element.onclick = function() {
// what to do when that element is clicked
};
for example:
<!DOCTYPE html>
<html>
<body>
<div id="thediv">Click me</div>
<script>
document.getElementById("thediv").onclick = function() {
alert("Awww... why did you do that?");
};
</script>
</body>
</html>

you have to bind an eventhandler to the element. you can do this inline with an onclick eventhandler. Also you can't use the name var because it is a reserved word in javascript.
html
<a id="mylink" href="#" onclick="handleMyClick();">Click me</a>
javascript
var myvar=3;
handleMyClick(){
if(myvar==3){
alert("you clicked the link and myvar is 3");
}
}

Related

changing class name and sending parameter in javascript

I would like to change the class of a tag and send a parameter i to the myFunction the tag is without id or name:
<a class="active" onclick="myFunction('i')"></a>
<script>
function myFunction(obj) {
}
</script>
using this in the function like myFunction(this,'i') doesn't work.
using this in the function like myFunction(this,'i') doesn't work.
That should work, you just need to amend the function to accept the element as an argument.
However you should note that on* event attributes are massively outdated and should be avoided where possible. Use unobtrusive event handlers instead:
Array.from(document.querySelectorAll('a.active')).forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
console.log(this.dataset.foo);
});
});
One
Two
Three
Update:
You mentioned in the comments that you're going to use jQuery AJAX, so you can simplify above with jQuery:
$('a.active').click(function(e) {
e.preventDefault();
console.log($(this).data('foo'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
One
Two
Three
You can do something like this:
function myFunction(obj) {
var data = obj.attr("data-param");
obj.removeClass("active");
alert(data);
}
$(document).ready(function(){
$(".test").on("click", function(){
myFunction($(this))
});
});
<a class="test active" href="javascript:void(0);" data-param="i">test</a>
Fiddle:
https://jsfiddle.net/u81g6qk4/10/
You can pass a reference to an HTML element by putting this is the function. Then you can use the element reference to do stuff to it without needing a id or name attribute.
someOtherClass is an assumed variable that contains the name of the class you want to add. Change it to whatever class or variable you want to use.
<a class="active" onclick="myFunction(this, 'i')"></a>
<script>
function myFunction(obj, param2) {
$(obj).removeClass("active");
$(obj).addClass(someOtherClass);
}
</script>
Use this if you do not want to use Jquery
<a class="active" onclick="myFunction(this, 'i')">Click Me</a>
<script>
function myFunction(element, str) {
console.log(str);
element.setAttribute('class', 'clicked');
}
</script>

Javascript Execute onclick event stored in variable

I've created the function below to identify an onclick event which is dynamically generated with each page load. I'm able to get the onclick event into a variable (developer console output shown below). I want to execute that onclick event but can't find a good way of doing that. Any assistance is appreciated.
"ƒ onclick(event) {
mstrmojo.dom.captureDomEvent('*lK1129*kWA92AF1C396244F28902B3171F9642E57*x1*t1530820506700','click', self, event)
}"
function applyAll() {
//Get the self Link to click it
var linkBys = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode");
// loop through each result
for(y = 0;y < linkBys.length;y++){
// retrieve the current result from the variable
var linkBy = linkBys[y];
// check the condition that tells me this is the one I'm looking for
if(linkBy.innerText.indexOf("link") !== -1){
// Find the right class
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].onclick;
console.log(idy);
}
}
}
If the property 'onclick' is defined as a function, you can just run it as a function.
var idy = document.getElementsByClassName("")[y].onclick();
You could also handle it another way:
var idy = document.getElementsByClassName("")[y].onclick;
idy();
onclick is not an event, it's a function which gets executed when element is clicked. If you want to simulate click you can do element.click()
If you used:
element.addEventListener('click',()=>...);
instead of:
element.onclick=()=>...
then all you have to do is:
document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].dispatchEvent(new Event('click'));
You can call the function returned , adding parens:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function foo() {
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[0].onclick;
console.log(idy);
idy();//like so
}
function alertMe() {
alert('Hello');
}
</script>
</head>
<body>
<button id="btn" class="mstrmojo-DocTextfield-valueNode" onclick="alertMe();">No click</button>
<button id="btn2" onclick="foo()">Click me</button>
</body>
</html>

How do I unobtrusivify this javascript?

I pulled this simple javascript function for showing or hiding a div from here. The function is:
function ReverseDisplay(d) {
if(document.getElementById(d).style.display == "none"){
document.getElementById(d).style.display = "block";
}else{
document.getElementById(d).style.display = "none";
}
}
This requires making a link like this:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
It's my understanding that having the link call javascript like that is bad practice. I'd like to make the javascript unobtrusive following https://stackoverflow.com/a/688228/2063292. But, that template provides a way to make some javascript execute for any link with a specified ID (e.g. all links with id="test" will call some function). I need to have a way to allow any link to pass the name of a specific div to the function, as in the original example, but I don't know how to do it.
I would prefer the ID of the div to be in the hash of the link:
Live JavaScript Demo
<a class="reversible" href="#arbitrarydivId">
Click to show/hide.
</a>
using
function ReverseDisplay() {
var divId=this.hash.substring(1), div=document.getElementById(divId);
div.style.display = div.style.display=="none"?"block":"none";
return false;
}
or
Live jQuery Demo
$(function() {
$(".reversible").on("click",function(e) {
e.preventDefault();
$(this.hash).toggle();
});
});
Older suggestions
window.onload=function() {
var links = document.querySelectorAll(".reversible");
for (var i=0;i<links.length;i++) {
links[i].onclick=ReverseDisplay;
}
}
using
<a class="reversible" href="#">
Click to show/hide.
</a>
To hide something else, try
function ReverseDisplay() {
var divId=this.getAttribute("data-div"), div=document.getElementById(divId);
div.style.display = div.style.display=="none"?"block":"none";
return false;
}
using
<a class="reversible" data-div="arbitrarydivId" href="#">
Click to show/hide.
</a>
In jQuery the whole thing would be
$(function() {
$(".reversible").on("click",function(e) {
e.preventDefault();
$("#"+$(this.data("div")).toggle();
});
});
Depends on how unobtrusive you want to be. You could do this (using jquery for shorthand purposes):
<a href="#" id="someUniqueId1">
Click to show/hide.
</a>
<a href="#" id="someUniqueId2">
Click to show/hide.
</a>
<script>
$("#someUniqueId1").click(function(){ReverseDisplay("#DivICareAbout");});
$("#someUniqueId2").click(function(){ReverseDisplay("#AnotherDivICareAbout");});
</script>
But then you need to specify each and every link in your javascript. So I would recommend being a little more obtrusive, not with JS but with the href. Like this:
HTML:
<div id="foo">I am foo</div>
<div id="bar">I am bar</div>
<a class="reverselink" href="foo">Click to show/hide.</a>
<a class="reverselink" href="bar">Click to show/hide.</a>
JS:
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
$(function () {
$(".reverselink").click(function(e){
ReverseDisplay($(this).attr("href"));
return false;
});
});
See this fiddle: http://jsfiddle.net/V73uw/ (again, using jquery for shorthand. It's trivial to do with vanilla js too).
Use this javascript to do all that.
function processName(aName){
//do work like hiding.
console.log(aName);
}
var body = document.getElementsByTagName('body')[0];
body.addEventListener("click", function(event){
if(event.target.nodeName === "A"){
//do work with anchor element
processName(event.target.dataset.div);
}
event.preventDefault();
});
Then use this html as your links.
some link
You can define your javascript for this once then all the links only need data-div to send a name to processName.
Only bad thing is data attributes are really new for html so it might, or might not be what you want.
By the way. This is actually similar to how KnockoutJS works. You might want to try that out.

Onclick button doesn't function

i try to create a button when the page is load.
<!DOCTYPE html>
<html>
<head>
<script>
function createButton(){
var newButton = document.createElement("button");
newButton.onclick="document.write('Tasto premuto')";
var textButton = document.createTextNode("Premi qui");
newButton.appendChild(textButton);
document.body.appendChild(newButton);
}
</script>
</head>
<body onload="createButton()">
</body>
</html>
the button is created succesfully, but the function that I have associated with onClick event doesn't work. any ideas?
onclick expects a function, not a string:
newButton.onclick = function() { document.write('Tasto premuto') };
Please see this jsFiddle
Of course, you should be aware that document.write() completely clears the DOM of all current content, rather than simply appending the string to the existing content.
You're assigning a string to function pointer:
Change:
newButton.onclick="document.write('Tasto premuto')";
To:
newButton.onclick= function(){ document.write('Tasto premuto') };

Get id of a span in JavaScript.

I want to get the span id in JavaScript following code always returning M26 but I want different values on different click M26 or M27:
function clickHandler() {
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert(xsp);
}
}
<html>
<BODY LANGUAGE = "javascript" onClick = "clickHandler();">
<a href="javascript:void(0)"><u><b><span id=M26>2011-
2012</span></b></u></a>
<div id=c26 STYLE="display:none">
<a href="javascript:void(0)"><u><b><span id=M27>2012-
2013</span></b></u></a>
<div id=c27 STYLE="display:none">
</body>
</html>
The problem you are facing is that var xid= document.getElementsByTagName("span"); gets all spans on the page regardless of where you click.
To solve this problem you should just pass a reference to the clicked object within the function. For example:
<span id=M26 onclick="clickHandler(this);" >2011-2012</span>
Then in your javascript code:
function clickHandler(object) {
alert(object.id);
}
However it is a good idea to bind the events within javascript rather than inline in the html tags.
This article describes the different ways in which you can bind events to elements.
There are several ways to get the id of the element that has just been clicked:
Pass a reference to this to the handler:
onclick="handlerFunc(this);">
Or, better yet, pass the event object to the handler, this allows you to manipulate the event's behaviour, too:
onclick='handlerFunc(event);'>
//in JS:
function handlerFunc(e)
{
e = e || window.event;
var element = e.target || e.srcElement;
element.id;//<-- the target/source of the event (ie the element that was clicked)
if (e.preventDefault)
{//a couple of methods to manipulate the event
e.preventDefault();
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
You can use getAttribute() function for this...
function clickHandler() {
var xid= document.getElementsByTagName("span");
var xsp= xid[0].getAttribute('id');
alert(xsp);
}
<html>
<body LANGUAGE = "javascript" onload = "clickHandler();">
<a href="javascript:void(0)"><u><b><span id=M26>2011-
2012</span></b></u></a>
<div id=c26 STYLE="display:none">
<a href="javascript:void(0)"><u><b><span id=M27>2012-
2013</span></b></u></a>
<div id=c27 STYLE="display:none">
</body>
</html>
See working Demo

Categories