Basic HTML JavaScript function not working as intended - javascript

I'm wandering if anyone can help. Im doing some rather basic JS for a project but I'm an idiot and not sure how to do this element.
I've used an opensource word highlighting program i've found online which works when i input a string to be highlighted, but when i input "input_id.value" which is a working (tested) value of an input box, The highlighter doesnt work. I thought it could be that it's not updating i.e it only runs once so it will try to highlight no value as nothing has been inputted.
This is the code snippet:
<script type="text/javascript" src="../Resources/hilitor.js"></script>
<script type="text/javascript">
var input = document.getElementById("input_id").value;
// global variable
var myHilitor;
document.addEventListener("DOMContentLoaded", function() {
myHilitor = new Hilitor();
myHilitor.apply("fox");
}, false);
</script>
This works correctly and higlights "fox" as shown in this image.
However when i change
myHilitor.apply("fox");
to
myHilitor.apply(input_id.value);
nothing is highlighted at all. I tried putting the whole thing into a function like an idiot but that also doesnt work
<script type="text/javascript" src="../Resources/hilitor.js"></script>
<script type="text/javascript">
function searchFunction(){
var input = document.getElementById("input_id").value;
// global variable
var myHilitor;
document.addEventListener("DOMContentLoaded", function() {
myHilitor = new Hilitor();
myHilitor.apply("fox");
}, false);
}
</script>
The function is called by
<button onclick="searchFunction()" class="button"></button>
I'm truly dumbfounded, any help would be very appreciated. Thankyou :)
Thanks all for the helpful contributions, Problem is solved I'm waiting to be able to accept answer

document.addEventListener("DOMContentLoaded", function() { causes a function to run when the DOMContentLoaded event happens (which is about when </html> is parsed as the document loads).
You haven't shown how searchFunction is called, but odds are that it is when a button is clicked.
That will happen after the DOMContentLoaded event has occurred so the condition for the function running never happens.
Don't include that condition.

Your variable is called var input but you're using input_id here myHilitor.apply(input_id.value) ;

You have declared var input = document.getElementById("input_id").value;.
But while calling myHilitor.apply(input_id.value); you are passing input_id.value. You should pass just input.
Like myHilitor.apply(input);

Related

.click() Function doesn't Triggered

Body onload triggers a function called "autoClicker" function to click a selected "span" element. It alerts which mean function is calling normally. I console logged the element which I checked, I'm choosing right. In last step It won't appears to be clicked, because If click happen, below options will be available.
Dears, I couldn't find out why its not click'ing and Im expecting your valuable contributions.
the function I added to theme.js file
$(function autoClicker(){
console.log("it works!");
var x = document.getElementsByClassName("variant-text")[0];
x.click();
});
I want to choose first "variant-text" classed element, you may find in here
This is sneakershop website, I want to automatically choose colors, because there is already one color option in each product and its loading with XML service, we cant change it it refreshes in a specific period.
Any help appreciate it.
I would imagine the issue is that you load theme.js first
<script type="text/javascript" src="//st2.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/theme.js?revision=7.1.3.2-5-1625248516"></script>
<script type="text/javascript" src="//st2.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/navigation-menu.js?revision=7.1.3.2-5-1625248516"></script>
<script type="text/javascript" src="//st3.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/lazyload.min.js?revision=7.1.3.2-5-1625248516"></script>
<script type="text/javascript" src="//st3.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/jquery.elevatezoom.js?revision=7.1.3.2-5-1625248516"></script>
<script type="text/javascript" src="//st1.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/product.js?revision=7.1.3.2-5-1625248516"></script>
<script type="text/javascript" src="//st2.myideasoft.com/idea/hs/56/themes/selftpl_602d7702ef274/assets/javascript/rateyo.js?revision=7.1.3.2-5-1625248516"></script>
and most likely the click handler hasn't been attached yet when you simulate the click.
The first thing I would do to verify this, would be something like:
$(function autoClicker(){
console.log("it works!");
var x = document.getElementsByClassName("variant-text")[0];
setTimeout(() => x.click(), 3000);
});
assuming that works, I would find the file that adds the click handler, and make sure you run this after, or just create a new js file that you load last.
I think #dave is correct. You're trying to click on the element before it's been generated. setTimeout may work, although I never like using it because you're trying to predict how long it will take for a given element to appear which will not work in every use-case.
There are many ways to accomplish this, but MutationObserver and 'DOMNodeInserted' work. Be advised, DOMNodeInserted is deprecated so MutationObserver is the way to go, although it may not be available in older browsers.
The below worked for me using DOMNodeInserted:
function init(){
var containerParent = null, container = null, targetNode = null;
function Init () {
container = document.getElementById ("main");
targetNode = document.getElementsByClassName("variant-text")[0];
if (targetNode.addEventListener) {
targetNode.addEventListener ('DOMNodeInserted', OnNodeInserted);
}
}
function OnNodeInserted(){
document.getElementsByClassName("variant-text")[0].click()
}
};
init();
Will try to follow up with an example using MutationObserver

getElementById() not working

The following code is somewhere between my head tags:
<script type="text/javascript" src="js/jquery-2.0.3.js"></script>
<script type="text/javascript" src="js/homepage.js"></script>
Somewhere in the body:
<input type="text" id="registreervoornaam" name="registreervoornaam" placeholder="Voornaam">
In my homepage.js:
window.onload=function(){
var regname = document.getElementById("registreervoornaam");
regname.focus = function() {
alert("bla");
};
};
Somehow I do not get an alert when focussing on the input field. Any idea's on what this might be? I added the function in the onload because otherwise regname will become null as the javascript file is parsed before the body.
What i would do to solve this:
See if the value returned by getElementById is null. If it is, it means that your element doesn't exist in the page. If that is the case, you may want to put all of your scripts at the end of the markup file, so that when the scripts are loaded, the whole DOM has already been loaded.
If you are already importing jQuery, why not use it? :D I would just do:
$("#registreervoornaam").focus(function() {
//do stuff here that you want to be triggered on focus
});
i just realised that there is no "focus" in plain js :/ I would use onfocus instead. Here are more details about it >> here
Good luck! :D
If you're going to set up the event handler that way, the property name is "onfocus", not "focus".
regname.onfocus = function() {
alert("bla");
};
And if you have jQuery on your page you could write :
$(function(){
$("#registreervoornaam").onfocus= function() {
alert("bla");
};
});

JavaScript onclick event is not working

A simple JavaScript onclick event is not working but I don't understand why, here is the code:
<button onclick="removeLol()">remove style</button>
function removeLol() {
alert("hello");
}
and here is a simple example: http://jsfiddle.net/YNQg6/1/
That's only because of the way how jsfiddle inserts the javascript.
Jsfiddle wraps your code into a function which limits the scope and protects the global namespace:
window.onload=function(){
function removeLol() {
alert("hello");
element.className = element.className.replace(" lol ", "");
}
}
If you tell jsfiddle to inject the code into the document body it works:
http://jsfiddle.net/YNQg6/13/
Or you could turn your "local" function in a global one:
window.removeLol = removeLol;
The code works just fine (just tried it on my server). Check your console for other errors that may be causing the script to not run

Update Javascript function content on postback

Here's my code
<script type="text/javascript">
function getNextScroll(i){
<asp:Literal ID="infiniteScrollTableJS" runat="server"></asp:Literal>
}
</script>
I am populating that Literal with some Javascript from the CodeBehind. This works great OnLoad. However, when I do a postback I have a problem. The Literal is updated on postback. The actual script that is inside the function actually gets changed (I can see it with Firebug). BUT, the function is unaware that there is new script in there, it just keeps running the old stuff.
So near as I can tell, I want to 're-initialize' the code inside the function after postback.
I know how to call a function after postback using add_endRequest.
This problem is not unique to .NET or anything. In fact, I have a simple example here -> http://jsfiddle.net/7JxY7/1/ 'Run Function' will always alert 'one' even after the script contents are changed.
I feel like jQuery probably has something that I could use, but searching around I have found nothing.
EDIT:
I tried the suggestion by mblase75. This works great in Javascript ( more importantly, now I understand why) , however, given this approach, I still can't get it working with the postback. Here is my updated code.
<script type="text/javascript">
function getNextScroll(i){
//some stuff
}
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
//mblase75 suggestion
getNextScroll = function (i){<asp:Literal ID="infiniteScrollTableJS" runat="server"></asp:Literal>};
});
</script>
I thought this would work, but of course, it has the same problem as my original method. The Literal is actually changed, but the function doesn't know about the change, it still has the original code
In JavaScript, a function is actually an object. So instead of trying to rewrite the <script> element with a string, replace the function (variable) name with a new function object:
<script>
goTest = function(){
alert('one');
}
function changeTest1(){
goTest = function(){alert('two');};
alert('ok');
}
</script>
<a onclick="goTest();">Run Function</a><br/>
<a onclick="changeTest1();">Change Function</a>
​
http://jsfiddle.net/7JxY7/2/

JavaScript variable scopes

I found a bunch of other questions about this topic, but for some reason they did not solve my "problem".
I have this little script I made of pure interest - and it works just fine, but something is bothering me. The script clears a text field onFocus and types "Write here" if nothing is entered onBlur. The script is as follows:
<html>
<head>
<title>JavaScript</title>
<!--Scripts-->
<script type="text/javascript">
<!--
function noValue() {
var _value = document.getElementById('input').value;
if (_value == "Write here") {
document.getElementById('input').value='';
}
}
function changeValue() {
var _value = document.getElementById('input').value;
if (_value == "") {
document.getElementById('input').value='Write here';
}
}
function dontLeave() {
var c_box = confirm("Do you want to leave?");
if (c_box == true) {
die;
}
else {
history.back;
}
}
//-->
</script>
</head>
<body onUnload="dontLeave()">
<form>
<input id="input" type="text" value="Write here" onFocus="noValue()" onBlur="changeValue()">
</form>
</body>
</html>
As you can see the variable _value is used twice - in "noValue()" and "changeValue()". This is what I want to change.
I thought that you could access a global variable from inside a function by not declaring it inside the function fx:
var i = 1;
function foo(){
i++;
return;
}
and the output would be 2 if you call the function. But when I declare and initialize the variable outside the function, the variable does not work from inside the functions - how come?? Have I misunderstood something here? :)
I also have another question:
As you can see I added a confirm box when you leave the page (I know this is annoying, I do not intend to use it, this is just an experiment) but I don't know how to not leave the page if the client presses "Cancel". How do I do so? :)
EDIT The first part of my problem is now solved - thanks!
But theres still the last part about the annoying confirm-box; does any of you know how to stop the client from leaving, so to speak?
To answer your first question, your problem with initializing _value is probably one of timing. By placing _value outside of a function, that line of javascript will be executed immediately. Since the javascript is in the head section, it will be executed before the input element has been loaded into the document. You can put that one line of javascript at the end of the document, after the input element has been loaded, such as this:
<body onUnload="dontLeave()">
<form>
<input id="input" type="text" value="Write here" onFocus="noValue()" onBlur="changeValue()">
</form>
<script type="text/javascript">
var _value = document.getElementById('input').value;
</script>
</body>
Now the javascript variable "_value" will be set properly and available to all of your javascript functions "globally".
Well, you can declare it outside the functions, but you need to update the value upon each function call (that is, each event). If you don't, then how will your event handlers know what it is?
If you put this line...
var _value = document.getElementById('input').value;
... outside of the functions, it will be in scope within the functions. I think the problem you're having though is that placing it there will cause it to be executed before the DOM is ready, and hence your 'input' element doesn't exist yet. Try either waiting for a dom load event, or place that script at the very bottom of the page (just inside the </body> tag).

Categories