referencing a dynamically created element in html - javascript

I have an input field(search_text), which shows the images (id="demo2") from a database when the user puts in more than 1 letter.
And then I have a draw function (draw()) that is supposed to do something when the image is being clicked, (after it got displayed from the database).
The problem is the image (id="demo2") does not exist in the Html DOM, only after the user has put in more than 1 letter.
Now, I have:
function myFunction(){
console.log('success');
alert("I am an alert box!");
console.log('success2');
var x = document.getElementById("demo2");
console.log(x);
x.addEventListener("click", myFunct);
console.log(x);
}
function myFunct(){
currentImg=document.getElementById("demo2");
draw();
}
function myFunction2(){
//alert("I am an alert box!");
var x = document.getElementById("search_text").value;
if (x.length >2){myFunction();}
}
which works when I slowley type in the searchterm and the alertbox comes and after that, when I click the image, the draw() function works.
When I take out the alert it won't work. Somehow the alert lets the user wait until the image is loaded/created. How do I achieve this without the alert?
Thanks!

You can use the jQuery function $.on() to bind an action to a not yet created element. You just specify it to be on an alement that exists when the code is running, such as the body element.
See the fiddle below. The HEY button wont appear until after 3 seconds, but since we bind the click event to it as described above, we wont have any problem.
//This is how you bind to a dynamically created element
$('body').on('click', '.myclass', myFunction);
setTimeout(function() {
var button = document.createElement('button');
button.className = "myclass";
button.appendChild(document.createTextNode("HEY"));
$('#button-cell').append(button);
}, 3000);
function myFunction() {
alert("It's working!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="button-cell"></td>
</tr>
</table>
Even though this works, I'd suggest you might look into adding your elements directly and then toggling their visibility.

use setTimeout to make it run in a separate thread which would be what alert does otherwise:
function myFunction2(){
setTimeout(function(){
var x = document.getElementById("search_text").value;
if (x.length >2){
myFunction();
}
},100)//keep minimal time.
}
Suggestion:
Why don't you add element to DOM toggle the display of an element instead of creating it after typing 2 chars?

Related

How to programmatically click on button, THEN do something?

I'm trying to write a script where I programmatically click a tab, which reveals more divs on the website, and then perform some actions on those revealed divs.
Right now, I have
document.getElementById("buttonid").click(); // which reveals another section of the webpage
console.log($("#idofnewdiv"));
...but it doesn't seem to see the new div. However, when I manually click on the button, console.log is able to properly print it out. Am I doing something wrong?
var button = document.getElementById("buttonid");
button.addEventListener("click", function(){
alert("Button is Clicked");
});
button.click();
too you can use it like this:
var mButton = document.getElementById("buttonId");
mButton.onClick(function(){
your code to execute here.
});
It doesn't look like your click function is doing anything. The following code assumes that all of the <div>s are already hidden.
var listOfDivsToReveal = document.getElementsByClassName("divsToReveal");
var listOfDivsIter = 0;
$("#thebuttonID").click(function(){
if(listOfDivsIter > listOfDivsToReveal.length){
//do whatever you do when all of your <div> tags are revealed
}
listOfDivsToReveal[listOfDivsIter++].style.display = "inline";//Or your desired display.
});

change attributes on button

I'm attempting to do a project in which I need to change attributes on a button. I have no code for you, but I still need help. Is there any way I can change a button that's already there so that the onclick attribute runs a different function from before? Thanks in advance.
I feel like all the answers so far miss the main point. Since you don't have any code examples, I'm guessing you'll find it hard to extrapolate out what everyone is saying.
So, one button, which when clicked, changes to another method, and when clicked again, changes back. I'm using the onclick attribute for simplicity, but as others have shown, using JavaScript .onclick or addEventListener is a better choice.
function function1(e) {
// Show where we're at
alert("function1 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function2(event)");
}
function function2(e) {
// Show where we're at
alert("function2 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function1(event)");
}
<button onclick="function1(event)">Click Me!</button>
You can of course change what function1 and function2 do, and add more changes (e.g. function 3 and 4), add logic for when to change, and so on.
use .onclick = function_name;
Demo :
document.getElementById('myButton').onclick = fun2;
function fun1() {
alert('I am from Function 1');
}
function fun2() {
alert('I am from Function 2');
}
<button id='myButton' onclick='fun1()'>Click me</button>
Yes, you can. There's only one thing to keep in mind:
An event on which you want the change to happen
Once you have identified that event, just bind it with JQuery's .attr() function to change any attribute.
Read more: http://api.jquery.com/attr/
Javascript Events: https://developer.mozilla.org/en-US/docs/Web/API/Event
Use jQuery like:
$("mybtn").click(function(){
$("#mybtn").attr({
"onclick" : "anotherFunction()",
});
});
Yes, it's possible. Check this fiddle: https://jsfiddle.net/gerardofurtado/ga3k7ssp/1/
I set a variable to 0 and this function for button 1:
bt1.onclick = function(){
i++;
myPar.innerHTML = i;
};
It increases the variable and displays the number.
But, clicking on button 2, it changes button 1 function:
bt1.onclick = function(){
i--;
myPar.innerHTML = i;
};
Now button 1 decreases the variable.
This other fiddle is similar, but using radio buttons, to show that you can set the original function of button 1 back: https://jsfiddle.net/gerardofurtado/8gbLq355/1/

How to stop a Javascript alert from reappearing in an infinite loop

The alert dialog created in the onclick reappears every single time I dismiss it in an infinite loop. This occurs in both Chrome and Firefox. This is my first day learning Javascript so please be gentle.
Is there a way to make the alert dialog appear only once?
This might be a problem with my computer. If so, what do I do to fix that?
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<p>"The text should turn red and one alert dialog should appear on click."</p>
<script>
function changeFontRed() {
var x = document.getElementById("demo");
x.style.color = "red";
console.log("Hello World!");
window.alert("Hello World!");
x.removeEventListener("onclick", changeFontRed(), false);
x.addEventListener("onclick", changeFontBlue());
}
function changeFontBlue() {
var x = document.getElementById("demo");
x.style.color = "blue";
x.removeEventListener("onclick", changeFontBlue(), false);
x.addEventListener("onclick", changeFontRed());
}
</script>
<button type="button" onclick="changeFontRed()">Click Me!</button>
</body>
</html>
Thanks guys.
These lines:
x.removeEventListener("onclick", changeFontRed(), false);
x.addEventListener("onclick", changeFontBlue());
You are calling the functions changeFontRed and changeFontBlue, not just naming them. The parenthesis () mark an invocation, and when the function is called again the dialog reappears.
Also (thanks to commenters) the event is named "click". Try this:
x.removeEventListener("click", changeFontRed, false);
x.addEventListener("click", changeFontBlue);
There are some problems with your code, but the infinite loop problem is in the line below:
x.removeEventListener("onclick", changeFontRed(), false);
More specifically, that part: changeFontRed(). Although you're trying to remove the changeFontRed event listener off your element, what you're really doing is calling that function and passing the return value to the removeEventListener function. And as soon as you're already inside the changeFontRead function, it will be calling itself recursivelly, until it turns into a stack overflow.
The removeEventListener function expects as the second paramenter a function reference, that will be called only when the button is clicked. So, to fix your problem, you must remove the (), and pass the function itself. E.g: removeEventListener('click', changeFontRed).
But there are other problems in your code, for example the "onclick" you're passing as the first parameter, because the addEventListener method won't understand it, since you shouldn't pass "on[event name]", but only "[event name]". So, it should be "click" only.
the second argument for remove/addEventListener should be a function, not the result of calling the function (as answered already).
first argument for remove/addEventListener should be 'click' not 'onclick'.
The button click will work the first time only, after that, you click the text that changes colour to change the colour again.
The second argument to removeEventListener and addEventListener should be a function. You're not passing the function, you're calling the function because you have () after it. Take that out.
function changeFontBlue() {
var x = document.getElementById("demo");
x.style.color = "blue";
x.removeEventListener("click", changeFontBlue, false);
x.addEventListener("click", changeFontRed);
}
Also, the name of the event is just click, not onclick.

Window.onload and ordering

In the code below, I can't seem to understand the ordering of events. When I load this in the browser, I get the alert before the first div renders and the .onclick event listener cannot find the translate_button element to attach to. I thought because of the use of window.onload, my script would execute after the above html loaded. Does this have to do with the inline javascript within the html?
<div id='MicrosoftTranslatorWidget' class='Dark' id='translate_button'></div><script type='text/javascript'>setTimeout(function(){{var s=document.createElement('script');s.type='text/javascript';s.charset='UTF-8';s.src=((location && location.href && location.href.indexOf('https') == 0)?'https://ssl.microsofttranslator.com':'http://www.microsofttranslator.com')+'/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&languages=es,pt,fr,it,tr,zh-CHS,zh-CHT,ru,de,en';var p=document.getElementsByTagName('head')[0]||document.documentElement;p.insertBefore(s,p.firstChild); }},0);</script>
<div class='disclaimer-link' id='disclaimer-link' style='display:none'>Disclaimer</div>
<script type="text/javascript">
window.onload = function () {
var button = document.getElementById("translate_button");
button.onclick = alert("lol");
};
</script>
You're assigning function execution. If you want to assign actual function you need something like
button.onclick = function() { alert("lol"); }
Another thing - you have ID defined twice for the DIV. Remove one and use the one that remains.

ColorBox onClick run JS Function

I am using ColorBox inline functionality and I have created a button which I've set to close the window when clicked:
$('.closebutton').live('click', function(){
$.fn.colorbox.close();
});
I have another function which I want to run when the button is clicked, so I've used:
<button class="closebutton" onclick="myFunction();">Close</button>
Problem is the myFunction is not working above.
Any ideas please?
UPDATE:
Here is where the code is:
<script type="text/javascript">
jQuery(document).ready(function() {
$(".inline").colorbox({inline:true, width:"50%"}); //for colorbox inline
$('#cboxClose').remove(); //remove popup window close button
$('.closebutton').live('click', function(){
$.fn.colorbox.close();
myFunction();
});
Adding myFunction(); before or after $.fn.colorbox.close(); is not working
myFunction code: (This goes after the code above on the page)
<script type="text/javascript">
function myFunction() {
$("#ajax-form").submit(function(){
$.post("update.php",
$("#ajax-form").serialize(),
function(data){
$('#jqm').attr('src',
$('#jqm').attr('src'));
}
);
return false;
});
}
</script>
UPDATE 2:
I'll try to explain better: I have a form and input on the main page that works find, so when you add some text to the input box and submit then form then the value of the input is submitted.
Now, when I put that same input in the inline area of colorBox so that it appears inside the popup window the value is not submitted. I've tried grabbing JS errors on firebag but cannot see anything there.
Hope this helps.
Why not just add myFunction() before $.fn.colorbox.close();? That way you can be sure what order things are handled in.
Instead of using inline javascript, you could simply do something like this :
$('.closebutton').live('click', function(){
$.fn.colorbox.close();
myFunction();
});
I believe the problem is that myFunction() (the onClick attribute) is being overridden by jQuery. If you want your function to execute whenever a .closebutton is clicked just use:
$('.closebutton').live('click', function(){
$.fn.colorbox.close();
myFunction();
});
If its only for that button, try adding an id to that button and:
$('.closebutton').live('click', function(){
$.fn.colorbox.close();
if($(this).attr('id') == 'exampleID')){
myFunction();
}
});
Ok so, after reading your update #2, I understand that actually your problem is not that the myFunction code doesn't execute right.
The problem is that you moved your input inside the colorbox, so its value doesn't submit with the form, wich is normal because the input is now outside the form.
You could either simply move your whole form inside the colorbox, or use javascript to copy the value of the input you moved outside of your form in a hidden input.

Categories

Resources