How to call external javascript from URL inside function - javascript

I'm will try to make my previous question a little more clearer.
So I have to CPA offer from my CPA network using tag.
<script type="text/javascript" src="https://megadownloder.com/script_include.php?id=372715"></script>
and
<script type="text/javascript" src="https://megadownloder.com/script_include.php?id=372716"></script>
Now, I want it to randomly call and choose between the two when the user click the download button.
Example scenario:
When a user clicked download button, the <script type="text/javascript" src="https://megadownloder.com/script_include.php?id=372715"></script> will be called.
When a new user clicked download again the <script type="text/javascript" src="https://megadownloder.com/script_include.php?id=372716"></script> will show.
In ramdom manners.
I hope I make my question clear and you guys can help me. Thank you very much.

Just give your script tag an id and then read the src attribute.
With slice cut of the last character, and add 5 + (0 or 1 random) to the string again.
So the result will be 372715 or 372716 as the id.
If there is no JS active, the src is still valid, but only with this id: 372715
As a side note:
This won't work in your case. The time you manipulate the script src attribute, the script was already loaded. So you should do this on server side.
var dlScr = document.getElementById('dl-script');
dlScr.src = dlScr.src.slice(0, -1) + (5+Math.round(Math.random()));
<script id="dl-script" type="text/javascript" src="https://megadownloder.com/script_include.php?id=372715"></script>

You just need to round it up using Math.round. Math.random will give you a number between 0 and 1. Rounding it will ensure it will be 0 or 1. After that you can use it strait in the if statement, because 0 is false, and 1 - and everything not 0 actually - is true, in case of numbers. By negating you could get true/false instead: !(Math.round(Math.random())), of course in reverse order, but because it's random, it does not matter. But if that bothers you just add extra ! to negate it again like: !!(Math.round(Math.random())).
But if you need more than two outcomes, just multiply Math.random by the number of outcomes minus one. For example for a three way you could use: Math.round(Math.random() * 2). But then you'll have to use if statement like in your example.
In case you need 1 or 2 as outcomes, just add one to the random number like: Math.round(Math.random() + 1). This will return 1 or 2.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function chose() {
// Rounding up like: Math.round(Math.random()).
// Will return 0 or 1.
// By negating you could get true/false instead:
// !(Math.round(Math.random()))
// !0 > true
// !1 > false
// For a three way (or more) random switch use:
// Math.round(Math.random() * [ways - 1]).
// Will return 0, 1 or 2.
// For a case where you want 1 or 2 as results:
// Math.round(Math.random() + 1).
// Will return 1 or 2.
return Math.round(Math.random() + 1);
}
function GetResult() {
if ( chose() === 1 ) {
OfferOne();
} else {
OfferTwo();
}
}
function loadScript ( id ) {
$('<scr'+'ipt type="text/javascript" src="https://megadownloder.com/script_include.php?id=' + id +'"></scr'+'ipt>').appendTo(document.head);
}
function OfferOne() {
loadScript(1000000);
}
function OfferTwo() {
loadScript(2000000);
}
</script>
If your code uses document.write() and you do not want it to overwrite the whole page if called after DOMReady, to be safe put the whole script above into the <head>, and use this loadScript function instead, to ensure synchronicity!
<script>
function loadScript ( id ) {
document.write('<scr'+'ipt type="text/javascript" src="https://megadownloder.com/script_include.php?id=' + id +'"></scr'+'ipt>');
}
</script>

Related

jQuery: How do I check a number from string?

there is a class named:
<div class="level_11 price_level" style="display: block;">
I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.
I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.
I need to check the number and say if my number is lower then the number from the level_, then run the script.
let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1; // Don't touch this //
let logLevel = Level +1; // Don't touch this //
console.log(`Success āœ“ - ${IBuilding.length} buildings left`);
$.each(IBuilding, function(Index, Entity) {
let BuildingMissing = IBuilding.length - (Index + 1);
window.setTimeout(function() {
$.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success āœ“ - last building successfully expanded to level: ' + logLevel }`);
}, Index * 250);
});
});
Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"
Can anyone help me out? :/
You can get the level number like this:
let classname = $("div[class^='level']").attr("class").split(" ").filter(getClass);
function getClass(value) {
return value.startsWith("level_");
}
let level = classname.toString().substr(6);
console.log(level);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="level_11 price_level" style="display: block;">
I found this on link /buildings/ID/:
current level of building
Maybe I can check the Level from there?
The HTML section for that is:
<dd>
13
Ausbauen
</dd>

How to Change value of input after page loads?

I have used a range picker (Progress bar) to get measurements from the customers. I have set it's limit from 1 to 50 so it takes 1 value by default if user do not select it and user can add product to the cart without selecting range picker. Is there any way that we can change by default value on page load with javascript (No jQuery) to something that does not allow user to add product to the cart.
Link: https://cutt.ly/nrB4PAR
I am using this code now but it's not working. I want value to be null.
<script type="text/javascript" language="javascript">
debugger;
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1)
{
document.getElementById("tmcp_range_1").value = "";
}
</script>
UPDATED:
Iā€™m not sure I really understand why you need this, but you have to put that code in a function, then call an event listener.
function changeVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", changeVal);
Updating the input value after DOM loads will change the value.
function updateVal() {
var range_val = document.getElementById("tmcp_range_1").value;
if (range_val == 1) {
document.getElementById("tmcp_range_1").value = "22";
}
}
window.addEventListner("load", updateVal);
And also you need to change noUiSlider logic to update UI.
Ref link https://refreshless.com/nouislider/slider-read-write/

MathJax event just before a latex expression is typset

I have a MathJax sample at Demo sample, which works as expected. All it does is typset the latex expressions within a div having an id of mathDiv.
I need to execute some custom logic when the third latex expression is about to be typset i.e. when ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ is going to be typset.
Question
Can I execute some custom JavaScript just before the above latex expression get typset by MathJax and if yes, then how would I do it?
I was thinking there might be some event model associated with MathJax typesetting, but couldn't find any in the docs.
The same demo sample code is as below.
<h2>Math Test</h2>
<div id="mathDiv">1. Solve for x $$X^2-1 = 8$$.
<br>2. Evaluate the following limit: $$\lim_{x \rightarrow b}{ (x-10) }$$
<br>3. Is ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ ?
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
$(document).ready(function() {
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "mathDiv"]);
});
</script>
There are signals for when math is typeset (see this example), though the signals for HTML-CSS output are a bit more complicate than for the other output formats.
But there is another approach that may work better for you. You can register a preprocessor that will run after the tex2jax preprocessor has located the math in the page, and that will put your wrapper around the math at that point. Then when the math is typeset, it will be inside the wrapper automatically.
Here is one example for that:
<style>
#math0 {color:red}
#math1 {color:blue}
#math2 {color:green; font-size: 200%}
#math3 {color:purple; font-size: 75%}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
MathJax.Hub.Register.PreProcessor(function (element) {
//
// Get the math scripts created by tex2jax
//
var math = element.querySelectorAll('script[type^="math/tex"]');
//
// Loop through them in reverse (since this
// is a live list)
//
for (var i = math.length - 1; i >= 0; i--) {
//
// Get the script and any preview that preceeds it
//
var script = math[i];
var preview = script.previousSibling;
if (preview && preview.className !== 'MathJax_Preview') preview = null;
//
// Create the wrapper span and give it an id
// (If you will be typesetting more than once,
// you will need to keep a global id number
// and use that rather than i)
//
var span = document.createElement('span');
span.id = 'math'+i;
//
// Insert the wrapper in place of the script
// and append the preview and script to
// the wrapper.
//
script.parentNode.replaceChild(span,script);
if (preview) span.append(preview);
span.append(script);
}
},50); // use priority 50 so it follows the standard MathJax preprocessors
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS_CHTML-full"></script>
<h2>Math Test</h2>
<div id="mathDiv">1. Solve for x $$X^2-1 = 8$$.
<br>2. Evaluate the following limit: $$\lim_{x \rightarrow b}{ (x-10) }$$
<br>3. Is ${ x } ^ { 4 } = 81 $ if $ x^4 - 9 =0 $ ?
</div>
Here, the wrappers are styled to add color, and to scale the third and fourth expressions.
I hope the comments make it clear what is happening. This preprocessor will be run any time MathJax.Hub.Typeset() is called, so you can use that as normal.
Note that if the math is in the page initially, as it is here, there is no need to queue the Typeset() call by hand (as MathJax will typeset the page initially). If you are dynamically modifying the page, then you will need to do that.

Can't get sessionStorage to work correctly

I have multiple buttons that when they are clicked an image is loaded and the image is supposed to stay there based even when the page refreshes. When I use this the button with the highest setItem value always shows even if I click on other button. How do I fix this?
here is one of the scripts:
<script type="text/javascript">
var isImage1 = sessionStorage.getItem('2');
function showImage1() {
sessionStorage.setItem('isImage1', '2');
$("#loadingImage1").show();
$("#loadingImage").hide();
$("#loadingImage2").hide();
$("#loadingImage3").hide();
$("#loadingImage4").hide();
$("#loadingImage5").hide();
$("#loadingImage6").hide();
}
if(isImage1 == 2) showImage1();
</script>
and here is one of my buttons:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage1();form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />
Update: I have updated this line
var isImage1 = sessionStorage.getItem('2');
to
var isImage1 = sessionStorage.getItem('isIamge1');
but my issue still exists, that the isImage with the largest value stays even when i click the other buttons, so help is still needed.
In your session storage, you are setting the value of the 'isImage1' Item to '2'
sessionStorage.setItem('isImage1', '2');
But in your code to retrieve the value you are actually retrieving the item '2'
var isImage1 = sessionStorage.getItem('2');
You need to change your sessionStorage.getItem to reference 'isImage1'
var isImage1 = sessionStorage.getItem('isImage1');
Then you should get the value you are expecting.
There are loads of good jsfiddles on session storage. you may get some ideas from this one:
http://jsfiddle.net/gabrieleromanato/XLRAH/
Incidently; this is a very small value you are storing, why not store it in a cookie instead?
EDIT:
based on the fact that you have multiple functions exactly like this one, you are better off following Ken's solution, the only thing I would add is a wildcard to turn off the other images:
function showImage(imgNum) {
sessionStorage.setItem('Image',imgNum);
$("[id^=loadingImage]").hide();
$("#loadingImage" + imgNum).show();
}
showImage(sessionStorage.getItem('Image'));
The code in the buttons would then be showImage(1) instead of showImage1();
_Pez
By re-factoring the code a little you can do something like this:
/// setup some vars including max number of images
var maxImages = 6, i = 1, v;
/// now loop through and get the items for each image
for(; i =< maxImages; i++) {
v = sessionStorage.getItem('isImage' + i);
/// if in storage, call show image with the number to show
if (v !== null) showImage(i);
}
/// show image based on number
function showImage(num) {
sessionStorage.setItem('isImage' + num, '1');
$("#loadingImage" + num).show();
}
Also note that sessionStorage only deals with strings. So in order to check a specific number you need to convert it to one first parseInt(value, 10);.
But in this case the 1 that we set can be anything - it's just to store some value so sessionStorage doesn't return null.
In the button code you can change it to do this:
<input name="EPL/MECH DESIGN - TECHS" style="white-space:normal"
onclick="moveText(this.name);showImage(1);form1.submit()"
style="width: 275px" type="button" value="7SBD EPL/Mech. Design Techs" />

Creating Dynamic Javascript AJAX

Alright, I'm currently working to create on an account mainpage a applet to show each "kid" the user has registered to the site. My idea is simple :
Kid 1 / Kid 2 / Kid 3
As buttons (with style and such) when he goes on this page. When he clicks on one of those buttons/names, I use javascript to show the description of the infos of the kid, etc. When I click on another name, the current content closes and shows the new appropriate content.
The content is dynamically created, so the id's of the divs containing the info are named after the number of kids. Example : content_Info_Kid1, content_Info_Kid2, ... It doesnt matter how many kids there are, they will be named content_Info_Kid32 if need be.
Now, I'm not too comfy with AJAX and javascript in general. In fact, I am not at all.
My first idea was to do this in a separate javascript file.
$(document).ready(function() {
$("#content_info_kid1").hide();
$("#content_info_kid2").hide();
$("#content_info_kid3").hide();
$("#KID_1").click(function () {
if ($("#content_info_kid1").is(":hidden")){
$("#content_info_kid2").hide();
$("#content_info_kid3").hide();
$("#content_info_kid1").show("slow");
$(this).css("font-weight","bold");
$("#KID_2").css("font-weight","normal");
$("#KID_3").css("font-weight","normal");
}
});
$("#KID_2").click(function () {
if ($("#content_info_kid2").is(":hidden")){
$("#content_info_kid1").hide();
$("#content_info_kid3").hide();
$("#content_info_kid2").show("slow");
$(this).css("font-weight","bold");
$("#KID_1").css("font-weight","normal");
$("#KID_3").css("font-weight","normal");
}
});
$("#KID_3").click(function () {
if ($("#content_info_kid3").is(":hidden")){
$("#content_info_kid2").hide();
$("#content_info_kid1").hide();
$("#content_info_kid3").show("slow");
$(this).css("font-weight","bold");
$("#KID_1").css("font-weight","normal");
$("#KID_2").css("font-weight","normal");
}
});
});
Obviously, this is not dynamic. And I don't want to create 32 alternatives, of course. Can somebody point me the right direction to create a dynamic way to show my content based on the number of kids ?
EDIT (see bottom for updated on loading just one kid data at a time)
An example on how you could achieve that:
<style type='text/css' media='screen'>
button { margin-left:20px; display:inline; }
</style>
<script type='text/javascript' src='jquery-1.7.1.min.js'></script>
<script type='text/javascript'>
function loadKidData(kidID) {
switch (kidID) {
case 1 : $('#kName').text(' John Doe');
$('#kNickname').text(' Speedy');
$('#kHobbies').text(' Booling');
break;
case 2 : $('#kName').text(' Mathews Doe');
$('#kNickname').text(' Slowy');
$('#kHobbies').text(' Basketball, baseball');
break;
case 3 : $('#kName').text(' Jackson Doe');
$('#kNickname').text(' J-DOE');
$('#kHobbies').text(' Archery');
break;
case n : $('#kName').text(' Enne Doe');
$('#kNickname').text(' The-Nanny');
$('#kHobbies').text(' Anything goes');
break;
default : $('#kName').text('');
$('#kNickname').text('');
$('#kHobbies').text('');
}
}
jQuery( function () {
$('.nav').click( function () {
loadKidData($(this).html().replace('KID ','')*1.0); // *1.0 same as parseInt(...,10).
})
});
</script>
</head>
<body>
<button class='nav' >KID 1</button><button class='nav' >KID 2</button><button class='nav' >KID 3</button>
<div id='KID_INFO' style='margin:20px auto; overflow:auto; ' >
<p>Name:<span id='kName'></span></p>
<p>Nickname:<span id='kNickname'></span> </p>
<p>Hobbies:<span id='kHobbies'></span> </p>
</div>
</body>
Sample at: http://zequinha-bsb.int-domains.com/kidsinfo.html
Now, as far as dynamically displaying the data, it will have to do with your resources: database? If so, you could read the data and pass it over:
$.get('url-of-the-database-reading-script',function (data) {
// assumed all data comes back formatted:
$('#KIDS_INFO').html(data);
});
I can/could help you further, more details would help. Are you using classic asp (.asp); php; etc?
EDIT:
Instead of this:
jQuery( function () {
$('.nav').click( function () {
loadKidData($(this).html().replace('KID ','')*1.0); // *1.0 same as parseInt(...,10)
})
});
Do this:
jQuery( function () {
$('.nav').click( function () {
$.get('your-data-fetching-url?kidID='+$(this).html().replace('KID ','')*1.0, function (data) {
//assumed the data comes back formatted:
$('#KIDS_DATA').html(data);
})
})
});
Note that I put a question mark at the end of the url; followed by the querystring kidID=
Give each "Kid" button the same class and use that for the click handler. From there, you can associate the "content_info_kid" with the "kid" button either by
1)Using the index of the element. The button for kid2 should be index 1 relative to its parent and the content_info for kid2 should also be index 1 relative to its parent.
or
2)Extract the number from the ID of the button.
Both approaches are documented below.
$('.kid_button').click(function(){
// get number from index (this starts at '0')
// if your kid #'s start at 1, you should add 1 to this
var id = $(this).index();
// OR...get number from id where id format is kid_{#}
var id = $(this).attr('id').split('_').pop();
// now we have the number to append to everything else
// we should also associate all "content_info" with a class
// which we will call "kid_content"
if($("#content_info_kid"+id).is(":hidden")){
// hide all of the 'kid_contents'
$(".kid_content").hide();
// show the one we want
$("#content_info_kid"+id).show("slow");
// normalize all buttons
$(".kid_button").css("font-weight","normal");
// bold this one
$(this).css("font-weight","bold");
}
});

Categories

Resources