Execute C# code inside JavaScript function when it's called - javascript

I want to execute a piece of C# code whenever I run a JavaScript function but it doesn't seem to behave the way I want it to here is an example:
Let's say that I have a variable property int Counter {get; set; } in the Model that I want to increment every time I run a JavaScript function:
<script type="text/javascript">
function MyFunction(){
//Do some stuff
#{Model.Counter++;}
}
</script>
What is really happening is that when the page loads #{Model.Counter++;} is getting executed regardless of not being called from the function.
And whenever I run the function again its ignoring it completely.
Meaning this piece of code #{Model.Counter++;} is getting executed once when the page loads and never again.
How do I fix that and make it execute every time I run the function?

You can use ActiveX control to execute Compiled program. but you should know that your html code only will work in IE.

You will have to create a hidden field for model.counter somewhere inside a view form
<input type="hidden" id="modelCounter" asp-for="Counter" value="#Model.Counter" />
after this you can change Counter using javascript
function MyFunction(){
//Do some stuff
var counter=$("#modelCounter").val();
counter++;
$("#modelCounter").val(counter);
}

I don't think what you want is possible (maybe with Blazor? - but that is WebAssembly).
Instead you can assign a new javascript variable to your model property.
E.g.:
<script type="text/javascript">
function MyFunction(){
//Do some stuff
let counter = #{Model.Counter};
counter++;
// Do some stuff with counter
}
// When you are done, post the counter back if needed on server side
</script>

Try This
#{
var a=Model.Counter;
}
do this outside the script
and inside the function or script
do
#a++;
or
var c = #a;
c++;
hope it works

Related

break out of setInterval loop javascript

I am new to javascript, and I am coding a game.
I would like to break out of the setInterval loop when a condition is met to display a game over screen. My code :
var timer = 0;
var i =0;
fond.onload= function()
{
timer = setInterval(boucle,50);
console.log("break");
}
function boucle()
{
i++;
if(i===4)
{
clearInterval(timer);
}
}
I never reach the break log because just after the clearInterval, the screen is stuck.
Thank you!
I am not sure what fond.onload represents in your code, but if you want the code to run when the page is loaded you should use window.onload or document.onload.
onload is a global event handler bound to all objects that gets executed when that object is loaded. I presume that in your case fond is never loaded as the rest of the code is fine, just never runs. It will run fine if you bind the function to window.onload.
You can read up more on that here

setTimeout fires twice or not in Javascript

I have this code:
window.setTimeout(function() {
let sudokuBodyWidth = $sudokuBody.outerWidth(true);
let sudokuBodyHeight = $sudokuBody.outerHeight(true);
console.log(sudokuBodyWidth + ',' + sudokuBodyHeight);
$sudoku.hide();
$welcomeOverlay.css({
width: sudokuBodyWidth,
height: sudokuBodyHeight
}).show();
}, 800);
window.clearTimeout();
I've put this code in a setTimeout because it takes a lot of time the DOM to load, so the JS code is to early with executing and returns 0 for the values (it's a huge codebase and I'm not 'allowed' to change the site structure to make the JS load later).
The problem is that this code runs twice. First, it returns the correct result, but then it returns 0 for both variables immediately after the correct values. As you can see, I've added a clearTimeout to prevent the execution to happen twice. But it keeps executing twice.
I've also tried:
let welcomeTimeout = setTimeout(function() {
// the code
});
clearTimeout(welcomeTimeout);
When doing this, the code doesn't execute at all.
window.clearTimeout() will do nothing because you are not passing the timerId witch get returned by window.setTimeout() and this should not run twice there is something else witch is causing this function to run twice
and in second one clearTimeout(welcomeTimeout); clears the timer that's why your code doesn't run
if you want to run your code after the document get loaded fully then you can use window.onload = function(){...}
or if you are using jQuery then you can also try $(document).ready(function(){...})
It should execute only once check Ur code base if u r loading script two times mean while put clearTimeout code at the end in the ananymous function given to setTimeout function
Putting the code at the end of HTML executes it when the DOM is loaded.
Use this:
<html>
<head>
<script async src="..."></script>
...
</head>
<body>
...
...
<script>(function() { init(); })();</script>
</body>
</html>
Function init() will fire when the DOM is ready.
Also you're using setTimeout() wrong, take a look at this example.
var what_to_do = function(){ do_stuff(); };
var when_to_do = 3000; // 3000ms is 3 seconds
var timer = setTimeout(what_to_do, when_to_do);

processingjs reaching sketch value without function

Good afternoon everyone;
I am working with processingjs and I realize one characteristic feature of processingjs;
I have a sketch file called mysketch1.pde and inside of my sketch I just declared int x=5; for test purposes. Thus, mysketch1.pde includes a method called getX() which is a getter for x value.
Lets say, I want to reach this value and print it on my web page. If I write my java script like that I have a problem;
<script type="text/javascript">
var mysketch = Processing.getInstanceById("mysketch1");
if(mysketch==null){
window.alert("it is null");
}
else
window.alert(mysketch.getX());
</script>
In this code mysketch variable returns null all the time. (I am including my sketch before javascript on the head section)
However, If I put a button to my web page and call the same code as function it works perfectly;
<script type="text/javascript">
function click(){
var mysketch = Processing.getInstanceById("mysketch1");
if(mysketch==null){
window.alert("it is null");
}
else
window.alert(mysketch.getX());
}
</script>
<button type="button" onclick="click()">place</button>
I assume this stuation happends because somehow javascript works before my .pde file is loaded.I would like to display value of X after .pde is loaded automatically. Do you know how can I cope with this problem?
Regards,
You should put your code on the window.onload event:
window.onload = function () {
var mysketch = Processing.getInstanceById("mysketch1");
if (mysketch === null) {
window.alert("it is null");
} else {
window.alert(mysketch.getX());
}
}
One way to get around this would be to poll the getX() function until the sketch becomes ready, like setting a timeout to wait until the variable is not null. This approach could also be used to check when the sketch in general is ready, like having a function isReady(){ return true;} and waiting until it is not null to run the rest of your script.

clearInteval don't work

I use setInterval and clearInterval in js, when 1st page load
var timer_detail=setInterval(function page1_load(){
......
},5000);
When I go to 2nd page
function page2_load(){
clearInterval(timer_detail);
}
but timer don't stop and I don't know why?
Make the interval variable global replacing:
var timer_detail = ...
with
window.timer_detail = ...
This should fix any scope issues but if it doesn't then add an alert to the page2_load function to ensure the function is being executed when expected.
function page2_load(){
alert('page2_load');
clearInterval(timer_detail);
}
One the second page add
<body onload="page2_load()">
this will executed your function.
please not that I also got ride of the "+" in the function name. because you cant have symbols in a function name.
it should be
function page2_load(){clearInterval(timer_detail)}

Can a javascript if statement run without a function?

I dont know a whole lot about javascript and i was wondering if this script would run or do i need to put the "if statement" inside some kind of onPageLoad function to run this? Please help.
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
Sure it would run -- but it would depend on something else having run first so that time has a value.
For example, this would work (even though it's bad practice because it sets a property on window):
<script>
time = 10;
</script>
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
You would also find it impossible to guarantee that any variables you need for temporary processing are kept out of the reach of other scripts. To overcome this limitation, you can (and except in the most trivial of sites, should) wrap the code inside an anonymous function that is invoked on the spot:
<script>
(function() {
// your code here
})();
</script>
If you want to access DOM Elements you have to put the script tag at the end of the page. Or you use something like onload of the body tag (or an equivalent funciton in JS framework)
It would run, realize time is undefined, generate an error and halt operations from that point on.
If "time" is seted on server side, so, you may write onload property body dinamically like this:
<body onload="functionName(<?php echo()?>)">
and then:
<script type="text/javascript">
function functionName(time) {
if(time < 30) { ... }
}
</script>

Categories

Resources