Where to Specify Java Script in a asp:content page? - javascript

I had a html page where I was using java script to collapse and expand Gridview. However, I had to switch to a asp:content page(part of a master page) where I don't have head tag.
I tried specifying the java script inside the asp:content but it is not working.
Also, I tried specifying itmy master page still its not working.
How to deal with it any ideas?
Here is the script.
<script type="text/javascript">
function collapseExpand(obj) {
var gvObject = document.getElementById(obj);
var imageID = document.getElementById('image' + obj);
if (gvObject.style.display == "none") {
gvObject.style.display = "inline";
imageID.src = "~/ims/Images/bullet_toggle_minus.jpg";
}
else {
gvObject.style.display = "none";
imageID.src = "~/ims/Images/bullet_toggle_plus.jpg";
}
}
</script>

You can specify script at any place in your page. As soon as browser sees script tag it executes script inside it.
But in this case I think you should execute your code inside window.onload event handler because you need to wait until you markup is loaded and then you need to call your function. For example:
<script type="text/javascript">
window.onload = function(){
function collapseExpand(obj) {
var gvObject = document.getElementById(obj);
var imageID = document.getElementById('image' + obj);
if (gvObject.style.display == "none") {
gvObject.style.display = "inline";
imageID.src = "~/ims/Images/bullet_toggle_minus.jpg";
}
else {
gvObject.style.display = "none";
imageID.src = "~/ims/Images/bullet_toggle_plus.jpg";
}
}
collapseExpand("yourOfYourElement");
}
</script>
Or you can register calling your function after some event raises. For example:
document.onclick = function(){
collapseExpand("yourOfYourElement");
}

Related

How can I make an input change its src with an onclick?

I'm trying this and my background changes color (what I want) but the src of the input only changes on the second time I click it. how can I make it change the source on the first click? Also how can I change the src back to the original with a second click?
<input id="showHideContainer" type="image" src="on.png " height="3%" width="2%" alt="On" onclick="toggle();">
<script>
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
$('#showHideContainer').click(function(){
$('#showHideContainer').attr('src', 'off.png');
});
}
</script>
You need to determine the current state of the obj then toggle it with the other
$('#showHideContainer').click(function(){
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
});
Quick fix. You are now attaching anoter eventhandler on the first click on the #showHideContainer, that is why it's not firing the first time. This trimmed version of your code should get you the expected result, also see the other answer to look at the state of your element attribute:
document.getElementById('showHideContainer').onclick = function () {
divTest = document.getElementById('header');
if (divTest.style.display === "none") {
divTest.style.display = 'block';
} else {
divTest.style.display = "none";
};
$('body').toggleClass('style2');
var off = $(this).attr('src').indexOf('off.png')>-1;
$(this).attr('src', (off?'on.png':'off.png'));
}

Linking in jQuery Makes Other Script Not Work

I am still new to script, this my be a simple question.
On the site I am building right now I have some small script functions that work great, but when I linked in jQuery for a different function the first ones stopped working. If I remove the jQuery link they work again.
Here is the functions that I have currently:
This one is the one I need jQuery for, <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
// ~~~~~~~~~~ Header Background image rotation ~~~~~~~~~~ \\
$(document).ready(function(){
var header = $('.mainheader');
var backgrounds = new Array(
'url(img/rainbow.jpg)'
, 'url(img/chicks_on_grass.jpg)'
, 'url(img/cattle_on_pasture.jpg)'
, 'url(img/csa_bundle.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 10000);
header.css('background-image', backgrounds[0]);
});
This next function still works normally
// ~~~~~~~~~~ ShowOrHide Element Onclick ~~~~~~~~~~ \\
function showOrHide(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
This one does not work any more
// ~~~~~~~~~~ Form Email Hint ~~~~~~~~~~ \\
JotForm.init(function(){
$('input_4').hint('ex: myname#example.com');
});
All three of these functions are enclosed in <script language="JavaScript"></script> tag.
Then I have a third party JavaScript link that controls some things on a form that I have on the site. <script src="http://max.jotfor.ms/min/g=jotform?3.1.1667" type="text/javascript"></script> This does not work alongside the JQuery either.
I have no idea what is going on, spent all day working on it. Any help is appreciated.
This is a conflict issue, refer to this page for further documentation
do this:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var $j = jQuery.noConflict();
// ~~~~~~~~~~ Header Background image rotation ~~~~~~~~~~ \\
$j(document).ready(function(){
var header = $j('.mainheader');
var backgrounds = new Array(
'url(img/rainbow.jpg)'
, 'url(img/chicks_on_grass.jpg)'
, 'url(img/cattle_on_pasture.jpg)'
, 'url(img/csa_bundle.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 10000);
header.css('background-image', backgrounds[0]);
});
// ~~~~~~~~~~ ShowOrHide Element Onclick ~~~~~~~~~~ \\
function showOrHide(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
</script>

JS function that stops another JS function

I have two JS functions: a load() function that displays a progress bar and a kill () function that stops the execution of the load once the page is loaded.
Now when another page is loaded the progress bar is not displayed, knowing that the load function is called on every page.
Any hints on where the problem might be and if there is a way to fix it.
Here is my code:
<script type="text/javascript">
var count=0;
function load(i) {
j = parseInt(i);
document.getElementById("progressBar").style.display = "block";
count=count+1;
if (document.all) {
document.all.btn1.value=count+'%';
document.all.progressbar.pic1.width=2*count;
}
else {
document.getElementById("pic1").width=2*count;
document.getElementById("bar").width=count+'%';
}
if (count<100) {
setTimeout('load(j)',j);
}
if(count==100) {
document.getElementById("progressBar").style.display = "none";
count=0;
}
}
function kill(){
if (document.applets[0].isActive()) {
document.getElementById("progressBar").style.visibility = "hidden";
}
}
</script>
Thank you in advance !
In load() you're changing display to block, but in kill() you set visibility to hidden; you should set display to none instead, so it can properly be set to block again next time. Read about visibility.
Optimized code:
<script type="text/javascript">
var count = 0,
win = window,
doc = document,
progressBar = doc.getElementById("progressBar"),
t, j;
function load(i) {
j = parseInt(i);
progressBar.style.display = "block";
count++;
// no actual need to check if doc.all is available
// just select through id
doc.getElementById("pic1").style.width = 2*count;
doc.getElementById("bar").style.width = count+'%';
if (count < 100) {
t = win.setTimeout('load(j)',j);
} else {
progressBar.style.display = "none";
win.clearTimeout(t);
count = 0;
}
}
function kill(){
if (doc.applets[0].isActive()) {
progressBar.style.display = "none";
}
}
</script>
If you assign setTimeout to a variable, you can use clearTimeout on it to stop it.
E.g.
set the timeout with
t = setTimeout('load(j)',j);
then stop it with
clearTimeout(t); Let me know if that helps, and makes sense :)

redirecting to other page with value in javascript via click

I want to create a Javascript file to do these operations:
Pass the current link to the other page
Click on hypertext or image that is created dynamically in JavaScript file to redirect
Just I want to have a Javascript link in the html body and not other thing same this :
<div>
<script type="text/javascript" src="JScript.js"></script>
</div>
And in the JavaScript file I have these:
var DivTag = document.createElement("Div");
DivTag.setAttribute('ID', 'MyDivTagID');
$(document).ready(function () {
$("$MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + window.location;
});
});
This is not working. Please help me.
Several issues
you never added the div to the page
you used $ instead of # to access the div by ID
you do not consistently use jQuery
Plain JS: DEMO HERE
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
DivTag.innerHTML="Click";
DivTag.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
document.body.appendChild(DivTag);
}
Using linked image:
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
var anchor = document.createElement("a");
anchor.href="#";
anchor.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
var img = document.createElement("img");
img.src="image.gif";
img.style.border="0";
anchor.appendChild(img);
DivTag.appendChild(anchor);
document.body.appendChild(DivTag);
}
jQuery: DEMO HERE
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>');
$("#MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
A small change to the jQuery code from mplungjan:
Change:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
To:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').find('#MyDivTagID').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
If you output e.currentTarget from the anonymous click handler function you get body since the event handler was attached to the body in mplungjan's solution. All I did was add .find('#MyDivTagID') directly after the .append() function so the click handler gets attached to the div and not the body.

Page resets after javascript function finishes

I'm doing a simple html page for a project.
I have a submission form.I use jquery to validate it (no sure if i'm doing ir right).
After the submission is validated,i want to save the user's details(name,password),in an array. The array is created when the script loads.
I added the function SubmitUser() to the onclick event,but when the function finishes,and adds the user,the page resets,and the variables are reset.
I wonder if someone could point out to me what i'm doing wrong.
Thanks in advance,
Boris
Here's the script code:
var userArray = new Array();
var passArray = new Array();
var userNumber = 0;
//Adding rules for validation
$(document).ready(function(){
$("#registerForm").validate({
rules: {
password: {
required: true,
minlength: 8
}
}
});
});
//Add a method to validate
$(document).ready(function(){
$.validator.addMethod("username", function(value, element) {
return this.optional(element) || /^[a-zA-Z]+$/i.test(value);
}, "Field must contain only letters");
});
//The function in question
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
//Function to switch between the different pages in the menu.
function toggle(id) {
if(id=='LoginPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='RegisterPage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
if(id=='GamePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('WelcomePage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('LoginPage').style.display = 'none';
}
return false;
}
If you're looking to override the form's natural submit behavior, you can do this:
$(document).ready( function(){
$('#registerForm').submit( function(e){
e.preventDefault(); // suppress natural submit behavior
submitUser(); // your function
});
});
And since you're already using jQuery, you can greatly simplify your toggle code. For each block like this:
if(id=='WelcomePage')
{
document.getElementById(id).style.display = 'block';
document.getElementById('LoginPage').style.display = 'none';
document.getElementById('RegisterPage').style.display = 'none';
document.getElementById('GamePage').style.display = 'none';
}
...you can instead do this:
if( id === 'WelcomePage' ){
$('#'+id).show();
$('#LoginPage, #RegisterPage, #GamePage').hide();
}
Or even more generally, handle all your toggling cases with one line:
function toggle(id){
$('#LoginPage, #RegisterPage, #GamePage, #WelcomePage')
.hide()
.filter('#'+id).show();
}
You can try adding this to your onclick event (on your 'submit' button):
onclick="javascript:return SubmitFunction();"
OR in your form tag (For normal submit button):
onSubmit="javascript:return SubmitFunction();"
Make sure you are returning true or false in your function. if false is returned page won't reset/refresh.
When the page refreshes or changes, the JavaScript variables are reset... Thats the unfortunate truth. Make sure the function that the form is on returns false to stop it from changing the page - so SubmitUser() should look like:
function SubmitUser()
{
if($("#registerForm").valid())
{
var user = document.getElementById('username');
userArray[userNumber] = user;
userNumber++;
alert('Registered');
}
return false;
}
Now, to change pages look at using jQuery.html (Link) to load content in without actually changing the page (or jQuery.load (Link) to load an actual file, like games.html):

Categories

Resources