Add onclick event to div in js - javascript

I'm trying to add a onclick event to a tag, but it isn't working. Can anyone tell me the correct way to add an onclick to this tag in js?
var cell = result.appendChild(document.createElement('abbr'));
cell.title = "cell number 1";
cell.className = 'chart-cell-type';
cell.addEventListener='onclick',(alert("clicked!")); //broken

As Alexis points out, your syntax is wrong. You want something like:
cell.addEventListener("click", function() {alert("clicked");})

Related

How to swap <div> elements by using "mouseover" event?

let wrapperSt = document.querySelector(".wrapper");
for(i=0; i<100; i++){
let divGroup = document.createElement('div');
wrapperSt.append(divGroup);
divGroup.className= 'pixel';
divGroup.textContent= '';
}
I've created the div element called "pixel" by using loop because, i need couple hundreds of them. (I'll use them as a little boxes that could change color)
But, i want these boxes ("pixel" div) to turn brown and sustain (style.backgroundColor ="brown";)
So, i created another div that will replace the previous div ("pixel").
let selectPx = document.getElementsByClassName("pixel");
selectPx.addEventListener("mouseover", function(){
let pxChange = createElement("div");
//This is where i got stuck!
})
I could not finish my code, i found it a bit complicated even if it is probably something very simple.
Any suggestions or piece of information would be very helpful. Thank you.
Not sure exactly what you are trying to do... I think you are trying to change the color of the div that your mouse is over? If so, you have a couple of issues with your code. Instead of adding the event listener to the list of divs, you need to add it to each one individually. Also, you should only need to change the background color of each element instead of creating a new one each time.
let selectPx = document.querySelectorAll(".pixel");
selectPx.forEach(pixel => {
pixel.addEventListener("mouseover", () => {
pixel.style.backgroundColor = "brown";
});
});
I'm not sure why you have to create a new div inside the first one. In your code, when you trigger the mouseover event you can get the div under the mouse and apply the style to it:
let selectPx = document.getElementsByClassName("pixel");
selectPx.addEventListener("mouseover", function(evt){
let divUnderMouse = evt.target;
divUnderMouse.style.backgroundColor ="brown";
})
I haven't tried it but it should work

Uncaught SyntaxError: Invalid or unexpected token in Html button

I create a button dynamically through javascript.
When I click on it I get the mentioned error.
The button is created like this:
var button = document.createElement("Button");
button.setAttribute("onclick", "FollowUser('" + name + "')");
button.setAttribute("id", "FollowUserButton");
When debugging it, I've tried to figure out what goes wrong when I create it. It seems to be in the part where I make the onclick event. Nothing seems odd when I set the id.
This output is returned:
button {disabled: false, form: null, formAction: "https://localhost:44398/Home/UserProfile?name=Test", …}
I'm providing my solution by presuming few things here. Please make sure to make the suitable changes in your code. The below code snippet will provide a base to the answer you want.
let name = "foo";
var button = document.createElement("BUTTON");
var text = document.createTextNode("Click me");
button.appendChild(text);
button.setAttribute("onclick", `FollowUser('${name}')`);
button.setAttribute("id", "FollowUserButton");
// Append this button to a node. For instance, append it to the body.
document.body.appendChild(button);
// Function added for testing onclick event.
function FollowUser(str) {
console.log(str);
}
I'm using template literals here to make the code more readable and less chaotic.

Javascript Generating Text into Textbox?

I wrote this little bit of code but I'm not sure why it's not working? It's supposed to take in the persons name and depending on what they selected it will output a website with their name at the end of it.
JSFiddle
http://jsfiddle.net/tQyvp/135/
JavaScript
function generateDynamicSignature() {
var dynSig = "";
var user = document.getElementById("usernameInput");
var e = document.getElementById("scriptListInput");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "example") {
dynSig = "http://example.com/users/";
}
document.getElementById("generateSignature").addEventListener('click', function () {
var text = document.getElementById('dynamicSignatureOutput');
text.text = (dynSig + user);
});
}
HTML
<select class="form-control" id="scriptListInput">
<option value="example">Example 1</option>
</select>
There are a few problems with your code, I'll try to list them all.
First, you never added the username input to your HTML.
Next, you seem mixed up on the way to access/set the text of an HTML input. You do this through the value field. For the username input, you forgot to access any property, so you'll need to change it to:
var user = document.getElementById("usernameInput").value;
You later used the text property of both the select element and the output. These should also both be value.
Another problem is that you've placed a listener inside a listener. Your outer function, generateDynamicSignature, listens for the onclick event of the button. This function only runs after the button is clicked. But inside this function, you attach a new listener. This inner listener will only run if someone clicks the button twice.
I've included these changes in a new fiddle:
https://jsfiddle.net/zdfnk77u/
where is usernameInput in your html?
in the if, use === instead of ==
If and when you add the missing "usernameInput" element in your HTML, all you'll have to do is...
dynSig='http://example.com/users/'+usernameInput.value;
I think part of the problem is that you want to access the value and not the text of input elements. So for text and strUser, you want to do text.value instead of text.text and such.
Also, based on the JSfiddle, you probably want to rewrite how you're using the document listener and the onclick of the html element. Every time the button is clicked it goes through the generateDynamicSignature and creates a listener to change the value, but doesn't necessarily change the value itself. If you move the logic of the generate function inside the click listener, that should fix most of your problems.
You create your generateDynamicSignature inside $(document).ready.
There are two approaches.
define function generateDynamicSignature outside
$(document).ready
or
bind your button.click to a handler inside $(document).ready
Do not mix these two.

Add JavaScript onClick to dynamically generated asp button

Background My page creates a list of objects based on rows of an SQL Database. For each object, a DIV is dynamically generated that contains a few items including a LinkButton and a further child DIV that is initially hidden. I want the link button to toggle the child DIV's hidden property. The JavaScript is not dynamically generated and is included in the ASPX page.
Problem I don't know how to make this generated LinkButton fire JavaScript that is included in the ASPX page and pass in the correct DIV's ID.
I'm guessing I need to add an attribute to the button like so:
myButton.Attributes.Add(reference to JS function + parameter of DIV's ID)
Maybe like:
myButton.Attributes.Add("onclick", "Show_Hide_Display('"<%="' +idString+ '".ClientID%>"')");
Where the button is given an attribute of a JS onClick handler pointing to the function "Show_Hide_Display" and a parameter of a DIV's ID that is calculated as the rendered ID. This syntax is incorrect though.
How do I write this so it calls 'Show_Hide_Display' and passes the ID of the current child DIV? All of the DIVs have the same ID apart from a number that references their row number, for example '"myDiv_" + counter.ToString'
The JavaScript I am trying to add a call to on the button:
function Show_Hide_Display(divID) {
var div = document.getElementById(divID);
var style = document.defaultView.getComputedStyle(div);
var display = style.getPropertyValue('display');
if (display == '' || display == 'block') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
Use the following syntax ...
myButton.Attributes.Add("onclick", "Show_Hide_Display(this.id);");
the above syntax allows to call the function with id as its parameter.
suggestion:
Try to write a common function which does not depend on generated ids of controls.
If this is not useful for your requirement, please post your code which might gives me a better idea.
If you are using jQuery, you could you jQuery delegate method.
$(document).on("click", "div.parent", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};
You need to implement getSubDivByParent according your DOM structure.
If you are not using jQuery, you need to attach event yourself. For each dynamically generated element. You need to manually add following script in your server code to register event.
... your html code ...
<script>
var elem = document.getElementById('new-created-element');
elem.addEventListener("click", function(){
var subDivId = getSubDivByParent(this);
Show_Hide_Display(subDivId);
};)
</script>
My suggestion is use jquery to achieve the functionality.
My solution works if you want to toggle the immediate div for the link.just call onclientclick method to toggle the div.
in linkbutton onclientclick="Show_Hide_Display(this)"
function Show_Hide_Display(id) {
$(id).next('div').toggle();
}
I hope this helps you .. Thanks

How to apply a click function, that changes the clicked div, to new div elements that are created

At the moment I am using the following code which on the click of an HTML div element, changes the inner text to "Hello World":
<div id = "one" onclick = "click('one')" >text</div>
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
This works as expected and changes the content of the div to "Hello World".
The problem I am facing is at the moment I am using the id as a parameter input for the function and so that also means that for each div element that I create I would have to manually write its id within the onclick function.
I am able to create div elements using the following script which takes a value from an HTML input box, turns into a number then uses that number in a for loop to create as many div elements as specified:
<script>
function numberOfDivs(){
var divValue = parseInt(document.getElementById("inputbox").value, 10);
for(var i = 1; i < divValue + 1; i++){
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
//newDiv.setAttribute("onclick", "click()");
newDiv.appendChild(divText);
var whatIAmAppendingTo = document.getElementById("one");
whatIAmAppendingTo.appendChild(newDiv);
}
</script>
Now the problem that I having is applying that click() function to any of the new div elements that have just been created so that the click() function only affects the div that I have clicked on. I have included the setAttribute line when I create the new div elements so there is no problem linking it to the click() function.
I believe that there are two options:
-Either create new code within the numberOfDivs() function and use the var i to create an id that would be different for each new div element that I create, since var i increases to a different value each time the for loop repeats.
or
-Rewrite the click() function so that instead of having to use an id paramater I can instead make the function applicable to all div's. I was roughly thinking along the lines of using the 'this' keyword within that code, or anything along those lines so that it applies to only the div element that I click on.
With both of these possible solutions I'm not quite sure how to execute them so it would be great help if someone would be able to give me an example how it works.
Any questions or clarifications feel free to ask.
The problem I am facing is at the moment I am having to use the id as a parameter input for the function ...
No, you don't; you can pass this into your function, which is a reference to the div the click occurred on:
<div id = "one" onclick = click(this) >text</div>
Then in your function, use that argument rather than document.getElementById(id):
function click(div){
div.innerHTML = "Hello World";
}
Now you can use the same function for multiple divs.
Note, though, that if you're creating the divs programmatically, there's a better answer than setting the onclick attribute: addEventListener (attachEvent on older versions of IE). In your function creating divs:
var newDiv = document.createElement("div");
var divText = document.createTextNode("text")
if (newDiv.addEventListener) {
newDiv.addEventListener("click", click, false);
}
else {
newDiv.attachEvent("onclick", click);
}
Within click, use this:
function click(){
this.innerHTML = "Hello World";
}
typo in innerHTML and onClick
text
<script>
function click(id){
document.getElementById(id).innerHTML = "Hello World";
}
</script>
and
<div id = "one" onClick ="click('one')" >text</div>
Could this idea be helpful? Create your divs as (example for id='one'):
<div class='mydivs' id='one' ></div>
And then, detect the click on the div using a class and one event handler using JQuery:
$(".mydivs").click( function() {
id = $(this).attr('id');
click(id);
});
<div id="one">
<!-- dynamically added child nodes -->
</div>
<script>
$.ready(function(){
$('#one').children().livequery('click', function(event){
this.innerHTML = "Hello world";
});
});
<script>
Here we can use livequery to add click handlers to child elements that will be added dynamically.
if you provide your newly created divs with a common class e.g. clickable you could do this
$function(){
//Any click event of the body element that originates from a ".clickable"
//will be handled by the provided handler
$("body").on("click",".clickable",function(){
$(this).html("Hello world");
});
//... anything else that has to happen on document ready
});

Categories