How to insert javascript function into html div - javascript

I have a .cshtml file with the following in the head tag:
<script type="text/javascript">
getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>
The reason I've inserted this is because this logic was already taken care of in another javascript file which I've imported in. Essentially what I need to do is change the link of a button depending on which platform the user is using. I've tried the following but this does not work (and even if it did, looks messy and I'm sure incorrect) but I can't seem to find a solution. Can anyone help please?
</div>
getPlatform()</script> id="mobilelink" class="btn"
</div>

One cannot write this:
getPlatform()</script> id="mobilelink" class="btn"
This is how it can be done:
</div>
<a href="" id="mobilelink" class="btn" </a>
</div>
<!-- Later in the page (ideally just before the end </body> tag) -->
<script>
document.getElementById('mobileLink).href = getPlatform()
function getPlatform () {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
</script>

why don't you check it when the page is loaded and change the href of the a tag accordingly? Like:
<a id = "mobileLink" href="">some text</a>
And
var getPlatform = function() {
if (Platform.Android) {
return "androidlink";
}
else if (Platform.IOS) {
return "IOSLink";
}
else {
return "other";
}
}
document.getElemenyById("mobileLink").href = getPlatform
//Or innerHTML, I don't really understand what you want to do

<script type="text/javascript">
function getPlatform() {
if (Platform.Android) {
document.getElementById('mobileLink').innerhtml = "androidlink";
}
else if (Platform.IOS) {
document.getElementById('mobileLink').innerhtml = "IOSLink";
}
else {
document.getElementById('mobileLink').innerhtml = "other";
}
}
</script>
the html,
</div id="mobilelink" class="btn" onload = "getPlatform()">
</div>
Right now I can only assume the results, that you need. This is one of the ways, inwhich you can return the result from a JS function to the html division. If the onload doesnt work, I'd suggest using an onclick = "getPlatform()" function since that is more aggressive in its notation.

this is incorrect approach.
I would recommend you put all scripts before closer </body> html-tag.
Then in your script you can write such code like:
const platform = getPlatform();
const mobilelinkEl = document.querySelector('#mobilelink');
mobilelinkEl.setAttribute("src", platform);
Make sure, that your script tag with src attribute set placed after script tag with getPlatform, and also make sure you have access to getPlatform function.
If you'll have additional question, write comments, I'll try to help you.

Related

How to run javascript in href?

I'm trying to get a string of script to run in an href so the link will redirect users depending on an if/else statement. My code:
<div id="editredirect">
<script>
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
</script>
</div>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:.initialize(document.getElementById("editredirect"));">Details</a>
I've tred do also do a function like this:
<script>
function editredirect {
if("[#authfield:Authentications_2_Region]" == "[#field:Location_2_Region_ID]"){
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else if ("[#authfield:Authentications_2_Region]") == "[#field:Location_2_B_Region_ID]"{
window.location.href = "member-details-edit?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
else {
window.location.href = "member-details?CID=[#field:Member_Caspio_ID]&Location_ID=[#field:Member_Location_ID]";
}
}
</script>
<style type="text/css">a.ex1:hover {color: #f18c21; text-decoration: underline;}
</style>
<a class="ex1" href="javascript:editredirect">Details</a>
Neither one will work. The first string returns a syntax error, the second tells me that "editredirect" is undefined.
Thank you!
EDIT
Praveen Kumar's suggestions were the best. The developer for the database I am using was able to get the application to do it without having to insert any script. However, they did say that the event listener would have also worked once I had my parameters correct.
You can use onclick and add the whole JavaScript logic:
Click me?
The best way is to use event listener like this:
document.getElementsByTagName("a")[0].addEventListener("click", function () {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}, false);
Click me?
This is better than using href. If you still want to run it in href, you need to create a function and run:
function aha() {
a = prompt('What\'s your name?');
if (a !== null)
alert('Welcome, ' + a);
else
alert('Bye Bye!');
return false;
}
Click me?
Note: In your code, you have used wrong notation. That's a syntax error. JavaScript functions have to be declared in a specific way. Follow that!

Internal Or External Link

I have a small problem with my links. I am trying to have it so when a link is checked, It uses javascript to handle page loading, This is fine, But before it loads the page I want it to take the URL it passed to JavaScript and check if it is external, If it is, Then alert them, Else just continue... heres the code I have so far:
JavaScript Document:
function loadPage(page, tag, ext) {
if (tag) {
fadeOut(tag);
setTimeout(function() {
if (page) {
console.log('Attempting To Buffer Next Page...');
} else {
console.log('ERROR: No Page To Buffer');
return;
}
if (ext) {
console.log('Loading Custom Extension');
if (checkExternal(page) == true) {
window.location = "external.php?url="+page+"."+ext
}
else {
window.location = page+"."+ext
};
} else {
console.log("No Custom Extension, Using .hmtl");
if (checkExternal(page) == true) {
window.location = "external.php?url="+page+".html"
} else {
window.location = page+".html"
};
}
}, 500);
}
else
{
console.log("ERROR: Tag Field Empty, Cannot Load Page")
};
};
Html Link:
<a onclick="loadPage('https://github.com/hbomb79/securitySystemPro/issues', 'body');" class="url">GitHub</a>
I have tried other results on here, But they all check the href attribute, I need to check a URL passed to a function that returns true if its external.
Anyone got any ideas?
By comparing a click event's .hostname with location.hostname you can easily check if a link is still local.
In the code below I apply a .click event to the class link : Meaning many elements can use the link class to be included in the event handling.
I personally find it preferable to use this method as it requires no changes to the main HTML document. That being said, you could always use onclick="function()" and get the same results.
$(".link").click(
function(e) {
if (e.target.hostname === location.hostname) {
console.log("going local")
return true;
} else if (confirm("Do you with to leave this website?")) {
console.log("Leaving Website");
return true;
} else {
console.log("Staying here");
return false;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<a class="link" href="http://somewebsite.com"> somewebsite.com </a>
<a class="link" href="#"> # (local) </a>
</body>
</html>

Mixed JS and HTML not working. Assistance?

Code below.
I'm complete balls at JS, and I have no idea what I did wrong. I /had/ it working, so that when the user input a name, it would display 'Name: {outputn}' on the next page after clicking submit. Afterwards, I put in a form html field below it, not displayed here because it was removed, and now it no longer works, even though it's the same code I had previously.
PS: In addition, if someone happens to know, is there a way I could add additional fields, ex gender, and have them be applied with the same submit button?
<div class="content active">Username: <input type="text" id="userName"></input>
<script>
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
setInterval(function(){
if( didClickIt ) {
didClickIt = false;
var o=document.getElementById("outputn"),v=document.getElementById("userName").value;
if(o.textContent!==undefined){
o.textContent=v;
}else{
o.innerText=v;
}
}
},05);
</script>
<button id="submitter" style="background:#ffffff;">Submit</button><br>
</div>
<div class="content"><p>Name: <div id="outputn"></div></p></div>
It seems to work for me here http://jsfiddle.net/NA9BM/2/
I added another element so you can see how you could do it with the same logic.
<div class="content active">
Username: <input type="text" id="userName"></input><br>
Email: <input type="text" id="email"></input>
<button id="submitter" style="background:#ffffff;">Submit</button>
</div>
<div class="content">
<p>Name:
<div id="outputn"></div>
</p>
<p>Email:
<div id="outpute"></div>
</p>
</div>
And the js
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
setInterval(function(){
if( didClickIt ) {
didClickIt = false;
var o=document.getElementById("outputn"), v=document.getElementById("userName").value;
var eo = document.getElementById("outpute"), e = document.getElementById("email").value;
if(o.textContent!==undefined && eo.textContent!==undefined){
o.textContent=v;
eo.textContent=e;
}else{
o.innerText=v;
eo.innerText=e;
}
}
},05);
You can try putting the script tag on the bottom to let the DOM load correctly before actually loading the script.
Place your <script> block after you have already declared your #submitter element - addEventListener() can't listen to events on nodes that haven't already appeared in the page.
Additionally, your code is overly complicated. Instead of checking to see if the button has been checked, just have the event fire your code directly when the listener is triggered:
document.getElementById("submitter").addEventListener("click", function () {
var o = document.getElementById("outputn"),
v = document.getElementById("userName").value;
if (o.textContent !== undefined) {
o.textContent = v;
} else {
o.innerText = v;
}
});
Your JavaScript code in the <script> block is executed as the page loads, so it will encounter and execute getElementById("submitter") before the <button id="submitter"> is encountered by the browser.
Move your code inside a DOMContentLoaded event-handler, then the submitter element will be available:
document.addEventListener('DOMContentLoaded', function () {
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
didClickIt = true;
});
});
Another option is to move the <script> block to the bottom of the page.
If you need to support older browsers, use window.onload instead of DOMContentLoaded.
Move your script part at the end of document.
When executing the line:
document.getElementById("submitter")
DOM was not ready (not all elements created) so your search for "submitter" produced NULL.
In fact, the proper way is to wait DOM to create all elements - see documentation for JavaScript or use jQuery.
<script type="text/javascript">
function init(){
//Your code
}
window.onload = init;
</script>

How to execute code when a div is clicked?

I've spent the last few hours trying to find the answer to this, but nothing seems to work...
I need to execute a piece of code when a div (or anything inside of it; including iframe content) is clicked. The following code should do it (when added into the div tag), but it doesn't seem to work.
onclick="if(typeof(_vis_opt_top_initialize) =='function'){ _vis_opt_goal_conversion(200); _vis_opt_pause(500);}"
The purpose is to execute a custom conversion goal:
<script type="text/javascript">
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
</script>
Any help will be greatly appreciated :)
I hate using inline js... hate it...
If you need to account for IE (<8), then you can't use addEventListener, so you can do something like this:
function bindListener(el,eventName,eventHandler) {
if (el.addEventListener) { // Anything but IE <8
el.addEventListener(eventName,eventHandler,false);
} else if (el.attachEvent) { // For IE <8
el.attachEvent('on'+eventName,eventHandler);
}
}
Then you can call it using something like this:
var ele = document.getElementById('idOfElement');
bindListener(ele, 'click', functionToCall);
Try using addEventListener. Link here. The Example on that page is exactly what you are asking for.
First give your div a unique ID
<div id="yourDivID"></div>
then set the onclick function in window.onload
var yourDiv = document.getElementById("yourDivID");
yourDiv.onclick = function() {
if(typeof(_vis_opt_top_initialize) == "function") {
_vis_opt_goal_conversion(200);
}
}
}
I write simple example for you:(j Query answer)
Html Code
<div class="test">Click</div>
JavaScript Code
$('div.test').click(function(){
alert("some");
});
Demo
Edited
JavaScript example
<html >
<script type="text/javascript">
function AttachAllDivEvents()
{
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++)
{
AttachDivClickEvent(divCollection[i]);
}
}
function AttachDivClickEvent(divObj)
{
divObj.onclick = function()
{
document.getElementById("count").innerHTML = parseInt(document.getElementById("count").innerHTML) + 1;
};
}
window.onload = AttachAllDivEvents;
</script>
<body>
<div>click</div>
<p id="count" style="font:bold 20px Times;color:red;text-indent:20px">1</p>
</body>
</html>

how do i make a hash run a function

i am new to javascript and i do not know how to do a hash but here is my code the code trigers curency to change on my website currently only byt clicking on a flag but i would like to use a hash like http://hostchick.co.uk/#ca to change the princing to canadian
<script type="text/javascript" language="javascript">
window.location.hash = "#ca"
{
function changeText(1);
function changeText(2)
}
</script>
<script language="javascript">
function changeText(idElement){
if(idElement==1){
document.getElementById('element'+1).innerHTML ='£1.99';
} else if(idElement==2){
document.getElementById('element'+2).innerHTML ='£2.99';
}
if(idElement==3){
document.getElementById('element'+1).innerHTML ='$3.15';
} else if(idElement==4){
document.getElementById('element'+2).innerHTML ='$4.73';
}
if(idElement==33){
document.getElementById('element'+1).innerHTML ='$3.16';
} else if(idElement==44){
document.getElementById('element'+2).innerHTML ='$4.75';
}
if(idElement==333){
document.getElementById('element'+1).innerHTML ='¥10.01';
} else if(idElement==444){
document.getElementById('element'+2).innerHTML ='¥29.94';
}
}
</script>
<li><a href="#" onClick="javascript:changeText(1);javascript:changeText(2)">
test
</a>
</li>
window.location.hash = "#ca"
{
function changeText(1);
function changeText(2)
}
is syntactically invalid JavaScript, so the assignment to location.hash never happens.
I'm not quote clear on what you're trying to do, but maybe
function changeText(1);
function changeText(2)
should be
changeText(1);
changeText(2);
Changing the hash does not cause the page to reload, so the server isn't involved. You can always use JavaScript to examine the hash and behave differently based on it.

Categories

Resources