This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 7 years ago.
I'm trying to target a button I've created by pressing another button. My code technically works, but due to the size of what I'm doing, I'm trying to put the function of the second button press in another js file. That where I'm running into problems. My code is below.
$("#webCoding").on("click", function() {
if ( $( ".webCodingID" ).length ) {
return false;
}
picture.attr("src", "img/webCoding.jpeg");
$(".target").empty();
$(".jumbotron").hide();
var buttonGroup = $('<div role="group" aria-label="...">').addClass('btn-group-vertical center-block')
var buttonPhilosophy =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Design Philosophy")
var buttonStack =$("<button type='button'>").addClass("btn btn-default btn-lg").append("Visit My Stack Overflow Account")
var buttonGithub =$("<button type='button' id='git'>").addClass("btn btn-default btn-lg").append("Look at what I've been doing on Github")
var webCodingID =$("<div>").addClass("trainingID")
$(buttonGroup).append(buttonPhilosophy).append(buttonGithub).append(buttonStack);
$('.target').append(buttonGroup).append(webCodingID);
// code for pressing created button is below.
$("#git").on("click", function() {
prompt("herro");
});
});
but I put this in another file (and get rid of the same code in the original js file), and nothing happens.
$(document).ready(function(){
$("#git").on("click", function(){
prompt("jungle boogie");
});
I can't figure out why. The js file is linked to my main page, I just can't get it to recognize buttons created by JS in another file.
You should bind the on to the body like so:
$("body").on("click", "#git", function(){
That should solve your problem I believe :)
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I'm stuck with an button, and can't understand why it isn't work.
$('#full-london').on('click', () => {
weatherPage.render('London');
});
'#full-london' is id of my button
weatherPage.render starts some jQuery code witch change my front page. This is tested in other case and it work correct.
This is the button:
<a id="full-london" class="btn btn-dark">Full forecast</a>
Any idea what is wrong?
Here is additional situation with search button who uses weatherPage.render and it work:
$('#search-city-button').on('click', () => {
const searchString = $('#search-city-input').val();
weatherPage.render(searchString);
});
searchString is search input
<div id="search">
<input type="text" id="search-city-input">
<a id="search-city-button" class="btn btn-danger">Search</a>
</div>
Here is what is weatherPage.render(); do https://pastebin.com/PLgrrYQ0
that makes perfect sense!!
you're adding your button dynamically, so when JS is parsing $('#full-london').on('click',... at that time there's no button on the page, so it can't attach the event to it.
function setEvents() {
$('#full-london').on('click', () => {
weatherPage.render('London');
});
}
make a function inside of your JS module (like setEvents) and call that function AFTER you add button to the page.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I am trying to make a follow button - and when clicked it sends an ajax request to my backend script and if it executes it returns a value that triggers the button's text to go from "follow" to "following" - and that part works just fine. But the jquery part where I send the user data in a data-attribute "data-follow" won't toggle with "data-unfollow". It only works when you refresh the browser which means you can only click the follow button, see it and the data attribute to change to "unfollow" but if you click once more it does not work. I cant figure it out and i've done my searching at the stack.
ERROR
TypeError: $(...).attr(...) is undefined
HTML
<button id="follow" data-follow="1, username1, username2">
<div><img src="images/loggedin/follow.png"></div>
<div>Follow</div>
</button>
JQuery
$("button[data-follow]").click(function(){
var button = $(this);
var data = $(this).attr("data-follow").split(",");
alert(data);
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Following");
var dataValue = $(this).closest("#follow").attr("data-follow");
$(this).closest("#follow").attr("data-unfollow", dataValue);
$(this).closest("#follow").removeAttr("data-follow");
});
});
$("button[data-unfollow]").click(function(){
var button = $(this);
var data = $(this).attr("data-unfollow").split(",");
alert(data)
button.find(" > div:last-child").animate({opacity: "0"},200, function(){
$(this).animate({opacity: "1"},200);
$(this).html("Follow");
var dataValue = $(this).closest("#follow").attr("data-unfollow");
$(this).closest("#follow").attr("data-follow", dataValue);
$(this).closest("#follow").removeAttr("data-unfollow");
});
});
$(document).on('click', 'button[data-follow]', function() {...});
$(document).on('click', 'button[data-unfollow]', function() {...});
Try it this way.
More Generic answer!
You can simply change the state of a button by removing, adding and toggling css classes via jQuery.
At (document.ready) check if follwing or unfollowed state via your ajax request and change the button's css class.
if(following){
$("#buttonID").toggleClass('following_btn');
} else{
$("#buttonID").toggleClass('unfollowing_btn');
}
Once clicked, process your code in the web service. Follow if unfollowed or Unfollow if followed. Then if you're rturning the updated state use that to re-update your button's css class accordingly. Or perform ajax call to verify the new state after the button click's ajax call finishes.
CSS:
.following_btn{
//your following style
}
.unfollowing_btn{
//your un-following style
}
Hope it helps!
This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I have a JS code in my WebApp and it's supposed to be triggered when I click a anchor and in fact it is, but only if I also use with $(document).ready.
If I use only the click event the script is not executed, but if I insert one more line in the JS file with $(document).ready the script is invoked as soon as the page load and also when I click the button. My intention in to call that script only when this particular button is clicked but I can't find a way to achieve this. Can you guys help?
<c:forEach items="${prontuario.atendimentos}" var="atendimento">
<li> ${atendimento.preenchimentoModeloAtendimento} ${atendimento.dataAtendimento} ${atendimento.tipoDeAtendimento.custo}
</c:url>"><i class="fa fa-arrow-circle-o-down fa-2x"></i>
<a id="aEditaAtendimento" href="<c:url value="/prontuario/editarAtendimento/${prontuario.prontuarioId}/${atendimento.atendimentoId}"></c:url>"><i class="fa fa-arrow-circle-o-down fa-2x"></i></a>
</li>
</c:forEach>
var abreEdicaoAtendimento = function() {
var idAtendimento = $('#idAtendimento').text();
var botaoAbreModal = $('#btnEditarAtendimento');
var campoIdPersistir = $('#atendimentoId');
alert(idAtendimento);
if (idAtendimento !== null) {
campoIdPersistir.val(idAtendimento);
botaoAbreModal.click();
} else {
alert('else');
}
};
$('#aEditaAtendimento').click(abreEdicaoAtendimento);
$(document).ready(abreEdicaoAtendimento);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have script that creates a div and adds a function that would remove this div on click, but it's not working.
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
}
Yes, yes, I KNOW this is not the best way to add a function, but I want to do it this way.
Just FYI - after executing create() the DIV appears fine. I checked and it does have proper ID and onclick="del(this.id)" attribute, but after clicking on it nothing happens. I double checked and added alert("I'm working") to the onclick attribute later and that worked. I'm not getting any errors. In the past .remove() was working fine but now it doesn't (Maybe that's because of the way I'm adding a function this time)
EDIT: It appears that del() is not executed when clicking on div.
You have this posted with jQuery, but you're showing mostly Vanilla. As to your initial problem,
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
$(element).html('<h1>DIV CREATED!</h1>').css('background-color', String.randColorHex());
}
create();
#someContainer > div { height: 10em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<div id="someContainer"></div>
Seems to work fine.
My guess would be that you have an issue with creating multiple divs by with the same ID, or possibly a scope issue.
Here's a couple steps you might take to double check the issue if using Google Chrome Dev Tools:
Open Console
Double Check function 'del' is globally available and the method you expect it to be by simply typing del. If you get an error, then your method may be displaced.
Another way you could check would be put the following in your onClick: try{console.debug(del);}catch(err){console.error('DEL DOES NOT EXIST!')}
Once you've established the method is within scope, if still not working, try the following:
Replace $("#"+el).remove(); with console.debug(el, $('#'+el))
This does a couple of things: It shows you that the Function is working, as well as gives you information of what's going on within.
If the first part of the console message (el) is the ID you expect, then check the 2nd part ($('#'+el)).
It should look something like: [div:#someID]
Open it and check it's length'. If0`, then it did not find that element.
If 1, then remove should be working fine. Put remove back in just above this console call, and ensure you now get a length of 0
Just FYI, this is how to do what you're trying to do using jQuery.
function create() {
var container = $('#someContainer'), // get container
// create div, everything in {} is an ATTR, then append it TO the container
div = $('<div />', { id: 'someID' + container.children('div').length+1 }).appendTo(container);
// just for visual, i use my own plugin to set a random background color
div.css('background-color', String.randColorHex());
}
$(function() {
$(document) // your click methods
.on('click', '#btnCreate', create)
.on('click', '#someContainer > div', function(e) { $(this).remove(); })
// trigger button once on load
$('#btnCreate').trigger('click');
})
#someContainer > div { height: 2em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<button id="btnCreate">Create</button>
<hr />
<div id="someContainer"></div>
This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 6 years ago.
I keep getting this error when i inspected the element of my button. The button is suppose to give a print view to page.
HTML Code:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
Javascript Code:
function printProducts(){
window.print();
}
Attached here is my code live in jsFiddle:
https://jsfiddle.net/PochMendoza/scj0q0dk/
"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick method of a button. That's really easy with JavaScript, we just need to give the button an id in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()" part anymore.
Now we need to set the printProducts function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>