What is the meaning of this code in Javascript - javascript

I am newbie to Javascript, I have difficulties getting the meaning of this code properly. I would like to share my thought over the code,and I need your guidance to understand it correctly.
<body>
<form>
<input type="button" value="Click Me!" id="say_hi" />
</form>
<script type="text/javascript" src="js_event_01.js"></script>
</body>
function hi_and_bye() {
window.alert('Hi!');
window.alert('Bye!');
}
var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_bye;
My understanding: the event "onclick" calls the function "hi_and_bye" when ID is "get_alerts". Similarly this could be applied to any event, and I can give an id attribute to any element and that id would be responsible to make an accessible corresponding input element.

Your understanding is correct. You could give an id to any DOM element, not only inputs. Then using the getElementById you could retrieve a reference to this element.
In this example that's what you are doing:
// Get a reference to a DOM element that has id="say_hi"
var hi_button = document.getElementById("say_hi");
// subscribe to the onclick event handler of the DOM element we retrieved on
// the previous line and attach this handler to the hi_and_bye javascript function
hi_button.onclick = hi_and_bye;
I don't think that the body of the function itself requires any more explanation: it will just display 2 alerts once after the other when this function executes.

Related

Why does prop('outerHTML') strip events, and how can I prevent it?

const continueButton = $("<button>Doesn't work.</button>").click(() => {alert("hello")});
$(".content").append(continueButton.prop('outerHTML'));
$(".content").append ($("<button>Works.</button>").click(() => {alert("hello")}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
</div>
The reason I'm asking this question is because I need to pass the string version of some HTML to a function. For that reason, I can't use .append. but when i use the code above, it seems that the click event no longer works.
How can I get the HTML as a string, but have the click event still work?
More context: I am using a library that expects me to add HTML to it as a string. But I want to add HTML with a button on it that functions when it's clicked. I'm using jQuery to create the HTML, but when I try to pass the HTML string to the library, the buttons don't function.
You can delegate the event to the content element and use button as target selector
// add delegated event listener before inserting buttons
$('.content').on('click', 'button', (e) => console.log($(e.target).text()))
const continueButton = $("<button>Doesn't work.</button>");
$(".content").append(continueButton.prop('outerHTML'))
.append ("<button>Works.</button>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
</div>
In line 1 the object has an event attached to it but this isn't reflected in HTML. Therefore when you add the outerHTML to an element, the browser creates a new element but events are not defined in the HTML so they don't exist.
If you embed the script inside the button HTML then it will work when you apply this HTML in different places: $('<button onclick="alert(\'hello\');">Test</button>').

Bind an html event to a function

How do I bind an html event such as onclick to a function myFunc(e){}?
I do not want to use document.getElementByClass or Id.
I do not want use jQuery.
Try this:
document.getElementsByTagName('body')[0].addEventListener('click', function(){alert("you clicked on the page")})
This adds an event listener to the body tag. Once you click on the page, it will fire the alert function.
You can get the elements by either class name, id and/or tag name:
document.getElementById('someId')
document.getElementsByClassName('someClassName')
document.getElementsByTagName('body')
Keep in mind, the "getElementsByClassName" and "getElementsByTagName" return arrays, so you might want to add the index like this
getElementsByTagName('body')[0]
document.getElementsByClassName('someClassName')[1]
...
If it's still the 1990s where you are and jQuery hasn't been invented, then sure:
<div onclick="myFunc">
</div>
First you must find the element on the page, for example var element = document.getElementById('clickme'), then you must add a listener to the click event element.addEventListener('click',function)

Can't pass a variable as an argument in a onClick function

I want to have a table and its cells are filled with data from MySQL.
The table have many TDs, which have an Id.
I want to pass the id of the cell to a function, so that I can edit its content:
document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList("Cell_ID")" value="Edit Action" />';
function SaveUpdateToActionList(Cell) {
alert(Cell);
document.getElementById(Cell).innerHTML = 'Here';
}
When I have alert(Cell); displayed, I see this sends the Text "Cell_ID", whereas I wanted to see the data ActionButton386 there.
Any help appreciated.
You can pass in the element being clicked by setting your onClick script to SaveUpdateToActionList(this);
Then, in the body of SaveUpdateToActionList, Cell will refer to the button that just got clicked. You can then walk up the DOM to get to the TD it belongs to.
You can try this:
document.getElementById(IndexedActionButton).innerHTML = '<input type="Button" name = "EditActionButton" id="EditActionButton" onClick="SaveUpdateToActionList()" value="Edit Action" />';
function SaveUpdateToActionList(event) {
alert(event.target.id);
document.getElementById(Cell).innerHTML = 'Here';
}
But if i understand correctly what you are trying to do, you shoud have a single event listner that catches bubling events from all cells, rather that attaching a an onclick to each cell....
Just register the event listener separately from specifying the innerHTML property:
Document.getElementById(IndexedActionButton).addEventListener('onclick', SaveUpdateToActionList);
SaveUpdateToActionList will be called with an event object as the first argument. You can access which element was clicked by checking the event.target property. For more information check out MDN - addEventListener documentation

how to add onclick event to create new element in javascript

I have created a label element. I need to add onclick event to that...
function a(me) {
var d=document.createElement("label");
d.id=me.id;
d.onClick="a(10)";
d.innerHTML="welcome";
document.body.appendChild(d);
}
HTML:
<label id="1" onclick="a(this)">aa</label>
<label id="2" onclick="a(this)">bb</label>
<label id="3" onclick="a(this)">aa</label>
actually what happens is when i click the any of three labels in html. another label is created and displays welcome. now when i click the newly created label "welcome" it does not display anything...... that is the onclick event added to newly created label is not working ....... any suggestion.................
You need to set d.onclick=function(){a(1);};, note that the case matters here (not "onClick").
[Edit]
Based on your comments and updated questions I've created a jsFiddle to demonstrate how you might turn your code into something that works.
d.setAttribute('onclick', 'alert(\'hello\');');
For creating an attribute to a HTML tag, sometimes we have to add this:
yourTag.src
yourTag.src = 'http://lolxd.com/404.png'
But there are special attributes, and them have diferents ways for editing:
yourTag.classList
yourTag.className
And there is the onclick attribute, wichwe can use it like this:
// The first way
obj.onclick = function () { alert('lalala') }
// With the Event Listener
obj.addEventListener('click', function () { alert('lalala') }, false)
// Or, a text-render way
obj.setAttribute('onclick', 'alert(`lalala`)')
I recomend you the Event Listener way, but try all :D

Removing the event listener on a button programatically

I have a button which is registered with a onclick event as shown
<Input type="Button" name="Register" Value="Register" onclick="CallMe();"/>
Is it possible to programatically remove or deregister the onclick event on this button?
You could set the onclick attribute to null.
var el = document.getElementById('inputId');
el.onclick = null;
or better just remove the attribute altogether with the removeAttribute() docs method of the element.
var el = document.getElementById('inputId');
el.removeAttribute('onclick');
you will need to add an id to the element though for this..
example code at http://jsfiddle.net/gaby/PBjtZ/
document.getElementsByName("Register")[0].onclick = ""
or
document.getElementsByName("Register")[0].removeAttribute("onclick")
Make sure to place this in a JS tag at the end of your document. So the DOM is available when this script is running.
the first example gets all elements with the name "Register" in your dom and returns the first, then it finds and sets the onclick attribute to an empty string. (could be null to)
the second example does the same, but removes the attribute "onclick".
Be careful if you have more then one element with the name "Register" you should do it like Gaby aka G. Petrioli told you to.

Categories

Resources