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
Related
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>').
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)
I have a block of list element which I need to add when "Add" button is clicked.
HTML:
<li>
<div><h3 >User name sss updated this.
<input type="button" value="X" class="delete"/></br></h3>
</div>
SOME TEXT HERE
</li>
jQuery:
$(".delete").click(function(){
$(this).closest("li").slideUp();
});
$("#addPost").click(function(){
var inData = '<li><div><h3>User name sss updated this.<input type="button" value="X" class="delete"></input></br></h3></div>';
$("#midContent ul").append(inData+'Sarthak</li>');
});
This block has a delete button and a jQuery function attached to it.
If the block already exist on the page, its working fine.
But, when I add this block using jQuery append, the block is rendered rightly, but delete functionality does not work on newly added block.
Where I am going wrong?
Also, what will be the better way to add this block than hardcoding in JS code? (just by referring the element already on page by using id or class)
You need to delegate events for dynamically created DOM nodes. You can delegate to the parent div, or the document itself.
$(document).on('click', '.delete', function(e) {
//your code here
});
The second argument in the click handler is the selector for which you are attaching the click handler.
Further reading: http://learn.jquery.com/events/event-delegation/
Try to use the event .on('click',function(){}) on dynamically created elements.
$(".delete").on('click',function(){
$(this).closest("li").slideUp();
});
$("#addPost").on('click',function(){
var inData = '<li><div><h3>User name sss updated this.<input type="button" value="X" class="delete"></input></br></h3></div>';
$("#midContent ul").append(inData+'Sarthak</li>');
});
Also, why create a variable when you could append the code directly?
I'm working on something that creates a form based on choices you give it (text/textfield/dropdown). When I create 2 dropdowns at once I am not sure how to write in a way that the computer can tell the 2 elements aren't the same, specifically when adding new inputs in my dropdown creator it can't tell multiple dropdowns apart.
Here's the Javascript function I'm using for it
$('#submit').on('click', function() {
$("select").each(function() {
switch($(this).val()) {
case "text":
$("#form").append('<p><input type="text"/> <button class="remInput">Remove</button></p>');
break;
case "note":
$("#form").append('<p><textarea></textarea> <button class="remInput">Remove</button></p> ');
break;
case "dd":
$("#form").append('<p><select id="ddFinal"><option></option></select> <button class="remInput">Remove</button></p>');
$("#ddCreator").append('<button id="ddAddInput">Add Another Field</button> <p class="ddP"><input type="text" name="ddText"/></p> <button id="ddSubmit">Submit</button>');
break;
}
});
$('#inputDiv').empty();
$('#ddAddInput').on('click', function() {
$("p[class*='ddP']").append('<input type="text" name="ddText"/>');
});
$('#ddSubmit').on('click', function() {
$("input[name*='ddText']").each(function() {
$('#ddFinal').append('<option>'+$(this).val()+'</option>');
});
$('#ddCreator').empty();
$('#ddFinal').removeAttr('id');
});
});
The problem is with the ddAddInput function because it doesn't specify between multiple p class="ddp" elements but I'm not really sure what I should be putting instead. Hope this question makes sense.
Here's the fiddle I'm currently working on http://jsfiddle.net/me74Z/15/
There are several flaws in approach that need to be remedied.
First: - element Id's are unique in a page by definition. Use classes instead.
Next, your event handlers are being added from within another event handler. If you were to change all the ID's you have to classes and the corresponding selectors in the event handlers, you would end up compounding events.
What compounding events means is if you add the same handler twice to an element, it will fire twice.
Using event delegation would be easier. Set up your event delegation outside of the current click handler for #submit
$(document).on('click', '.ddSubmit', function() {....});
Now, as for how to handle instances, within every event handler this is the element that is the target of the event.
Using $(this) and jQuery traverse methods you can work with the target's parent and siblings or whatever you need to do.
I would suggest you wrap each level in a container to simplify the traversals. I'll call container class row so that a generic traverse from an event target can look something like:
var someField= $(this).closest('.row').find('.someField');
WHen remove button is clicked, simply remove the parent row
I am trying to implement a function which changes style of element on click and remove it when unfocus. For ex: When element2 is clicked, it should remove class of other elements, and add class to the clicked element only.
<div class="dope" id="element777"></div>
<div class="dope" id="element2"></div>
<div class="dope" id="element11"></div>
<div class="dope" id="element245"></div>
<div class="dope" id="element60"></div>
.....(More are created automatically, numbers are not estimatable)
I couldnt know the element ids that are created. The only remains same is class.
I have tried this, but its an unprofessional approach.
$('#element1').click(function(){
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element1").blur(function(){
$("#element1").removeClass(dope);
});
$('#element2').click(function(){
$("#element2").addClass(dope2);
$("#element1").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element2").blur(function(){
$("#element2").removeClass(dope);
});
What is the best approach for automating this function, instead of adding click and blur (unfocus) function to ALL of elements ?
You can listen for click events on any div with an id containing the word "element', then target its siblings elements (those that are not clicked, without referring to them by id). This might do it:
$("div[id*='element']").click(function(){
$(this).addClass('dope').siblings('.dope').removeClass('dope');
});
Your jQuery could be vastly simpler if you leverage this and siblings:
Instead of:
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
It could be:
$('.dope').click(
function() {
$(this).addClass(dope2).siblings().removeClass(dope);
}
);
NOTE:
Do you have a variable called dope with the class name, or is dope the class name? If it's the classname, you need to put it in quotes: $(this).addClass('dope2'), etc.
If you are removing the class dope, then will want to add a class you can always use to select these elements (so that when you remove dope, it continues to work).
Button part:
$("div").click(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).addClass("dope2");
$(".dope").not($(this)).removeClass("dope");
}
})
Blur part:
$("div").blur(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).removeClass("dope");
}
}
I would recommend using the :focus css selector rather than using javascript to do what you are doing... Read more here. Instead of having a click listener, the focus selector will take care of that for you and automatically remove the styling when the element is out of focus.