Hide div with js, but without affecting html code - javascript

Let's say we have a div with id = '123'
Ho to make it invisible with js without affecting its html code?
So document.getElementById('123').style.display = 'none' is not an option.
JS only
UPD:
I just have interesting task! I have to hide some comments with js from guestbook , but when I change html code to hide it, Server somehow understands what I've done and redirects me to warning Page. So I have to do something with that.
UPD2:
I had obfuscated script on my page
function check_divs() {
var try_again = true;
var arr_divs = document.getElementById('content').getElementsByTagName('div');
if (arr_divs.length != divs_count) {
try_again = false;
} else {
for (var i = 0; i < arr_divs.length; i++) {
if ((arr_divs[i].style.display == 'none') || (arr_divs[i].style.position == 'absolute')) {
try_again = false;
};
};
}; if (try_again) {
setTimeout(check_divs, 998);
} else {
document.location.href = '/alert.html';
};
}
This one, so my solution was to clear all timeouts.

document.getElementById('123').style.visibility = 'hidden';
or
document.getElementById('123').setAttribute('style','display:none');
or
document.getElementById('123').setAttribute('style','visibility:hidden');
or if you have jQuery libraries
$('#123').css('visibility','hidden')
or
$('#123').css('display','none')
Any of that help?

Related

unable to get property 'style' of undefined or null reference for background colour

Hi I'm getting script error for below code. as I tried all the ways but no luck .
kindly help me as I'm very new to this field. atleast tell me where am I going wrong
<body onload="hightlightMoreLink(2210);hightlightMoreLink(2211);">
function hightlightMoreLink(groupID) {
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)       var moreLinkColumnElement = "";
var moreLinkElement = "";
if (groupID == 2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");        
moreLinkElement = document.getElementById("labelingMoreLink");
} else { 
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color = "#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
(getting error on this line)
moreLinkElement.style.color = "#26339f";
}
}
Here it is working...
function hightlightMoreLink(groupID) {
var isHightlightRequired = 1
var moreLinkColumnElement="";
var moreLinkElement="";
if (groupID==2210) {
moreLinkColumnElement = document.getElementById("MoreLinkTH");
moreLinkElement = document.getElementById("labelingMoreLink");
} else {
moreLinkColumnElement = document.getElementById("MoreLinkTHUnblind");
moreLinkElement = document.getElementById("labelingMoreLinkUnblind");
}
if (isHightlightRequired) {
moreLinkColumnElement.style.backgroundColor = "#26339f";
moreLinkElement.style.color="#fff";
} else {
moreLinkColumnElement.style.backgroundColor = "#f5f5f5";
moreLinkElement.style.color="#26339f";
}
}
hightlightMoreLink(2210)
First of all, you should create a fiddle so people can better understand the problem.
Checking your code though, I think the problem is in this line:
var isHightlightRequired = top.document.Main.isOtherLabelingCountriesPresent(groupID)
Check if it is return a boolean.
Aside from that, I think you should work with classes to manipulate the elements' styles. The onload you're putting on the body is not a good practice either. Jquery has a function for that purpose.
$( document ).ready(){
hightlightMoreLink(2210);
}
Another thing I would point out is the fact that you could use jquery to manipulate the elements. As is:
$("#MoreLinkTH").css("background-color", "#26339f");
$("#labelingMoreLink").css("color", "#fff");

Using $_GET with Jquery

I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have another somewhat related question, I'm not sure if I should make a new question for this as I'm fairly new to stackoverflow as well, but here it is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!
Here's the Javascript-solution:
function getParam(key) {
var paramsStr = window.location.search.substr(1, window.location.search.length),
paramsArr = paramsStr.split("&"),
items = [];
for (var i = 0; i < paramsArr.length; i++) {
items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
}
if (key != "" && key != undefined) {
// return single
if (items[key] != undefined) {
return items[key];
} else {
return null;
}
} else {
// return all (array)
return items;
}
};
if (getParam("email")) {
// ...
}
Regarding your second question you can use the following to determine if an element is visible:
var bool = $('.foo').is(":visible");
So to hide an element if it is visible you would do something like this:
if ($('.foo').is(":visible")) {
$('.foo').hide();
}
I'm silly and have answered my first question. I still have yet to have my coffee.
The following works, just insert it into the div that is to be displayed:
<div id="contactform" style="<?php if(isset($_POST['email'])) echo "display:block;" ?>">
content
</div>

Preserve a value of an element after change using jQuery

For internationalization support, I wrote code that changes the URL from #lang-select dropdown .The code is
$(document).ready(function(){
var sel = document.getElementById('lang-select');
sel.onchange = function(){window.location.replace($('#lang-select').val());};
});
the above code works fine and it changes the URL from http://0.0.0.0:3000/fr to http://0.0.0.0:3000/en.
Now I want to preserve the changed value, but without success. I have written the code below. I don't know why it is wrong/not working .
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
for(var shortLanguage in available_languages){
if(shortLanguage === languageInUrl) {
var langaugeOptionArray = $("#lang-select>option");
for(var i = 0 ; langaugeOptionArray.length > i ; i++){
if(langaugeOptionArray[i].label === available_languages[shortLanguage]){
langaugeOptionArray[i].selected = true;
return;
}
}
}
}
}
Please tell me what's wrong in above code and since what I am doing is not a new thing, please share what is the best practice to overcome this scenario.
Currently, I am using backend to accomplish this.
$(function() {
$('#lang-select').on("change",function(){
window.location.replace($(this).val());
});
});
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
var lang = available_languages[languageInUrl];
if (lang) {
var langaugeOptionArray = $("#lang-select>option");
langaugeOptionArray.each(function() {
if($(this).text() === lang){
$("#lang-select").val(lang);
return false;
}
});
}
}
I believe we can even do
if (lang) {
var opt = $("#lang-select").find('option[text="'+lang+'"]').val();
if (opt) $("#lang-select").val(opt);
}
Good luck

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):

GM_registerMenuCommand is not defined

everybody. I'm puzzled as to why I keep getting the error "GM_registerMenuCommand is not defined" when I try to run a userscript that I created. I have tried this in Firefox using Scriptish 1.0b9 and the latest version of Greasemonkey. I even disabled all addons except Scriptish to see if it was a conflict, but with no joy.
I'm including jQuery in my userscript using this template by Erik Vold. Before trying this template, I put the exact same code block in the template proposed by Joan Piedra and everything worked fine. Unfortunately, Piedra's template did not work in Chrome, which is something that I think is necessary, considering Chrome's growing userbase. The snippet that's throwing the error is below:
// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
// the guts of this userscript
function main() {
var isLevelupMove = false;
var isTutorMove = false;
var isTM = false;
var TMhead = $('#moves\\:machine');
var hasSecondEvo = false;
var hasFinalEvo1 = false;
var hasFinalEvo2 = false;
var header = $('.header-row').eq(1);
var TMmoves = new Array();
//This section deals with the user-defined colors
GM_registerMenuCommand("Color for pre-evolutionary-only moves", prevoColorPrompt);
GM_registerMenuCommand("Color for first evolution-only moves", evoColorPrompt);
if(localStorage.getItem('prevoColor') == null || localStorage.getItem('evoColor') == null)
{
localStorage.setItem('prevoColor', 'red');
localStorage.setItem('evoColor', 'orange');
}
var prevoColor = localStorage.getItem('prevoColor');
var evoColor = localStorage.getItem('evoColor');
function prevoColorPrompt()
{
var input = prompt("Please enter a desired 6-digit hex color-code for pre-evolutionary pokemon:")
localStorage.setItem('prevoColor', '#'+input);
}
function evoColorPrompt()
{
var input = prompt("Please enter the desired 6-digit hex color-code for first-evolution pokemon:")
localStorage.setItem('evoColor', '#'+input);
}
//This loop tests each 'th' element in a sample header row, determining how many Evos are currently present in the chart.
$('.header-row').eq(1).find('th').each(function(index)
{
if($(this).find('a').length != 0)
{
switch(index)
{
case 2:
hasSecondEvo = true;
break;
case 3:
hasFinalEvo1 = true;
break;
case 4:
hasFinalEvo2 = true;
break;
}
}
});
//All 'tr' siblings are TM moves, since it's the last section on the page
//This array puts only the names of the available TMs into the TMmoves array
TMhead.nextAll().each(function(index)
{
TMmoves.push($(this).children(":first").find('a').eq(0).html());
});
$('tr').each(function(index)
{
var moveName = $(this).children(":first").find('a').eq(0).html();
moveName = $.trim(moveName);
switch($(this).attr('id'))
{
case 'moves:level-up':
isLevelupMove = true;
break;
case 'moves:egg':
isLevelupMove = false;
break;
case 'moves:tutor':
isTutorMove = true;
case 'moves:machine':
isTM = true;
}
if(isLevelupMove || isTutorMove)
{
var babyMoveCell = $(this).find('td').eq(0);
babyMoveText = $.trim(babyMoveCell.html());
secondEvoCell = babyMoveCell.next();
secondEvoText = $.trim(secondEvoCell.html());
finalEvo1Cell = secondEvoCell.next();
finalEvo1Text = $.trim(finalEvo1Cell.html());
finalEvo2Cell = finalEvo1Cell.next();
finalEvo2Text = $.trim(finalEvo2Cell.html());
//This checks if evolutions have checkmarks
if(babyMoveText.length > 0)
{
if(hasSecondEvo && secondEvoText.length == 0 || hasFinalEvo1 && finalEvo1Text.length == 0 ||
hasFinalEvo2 && finalEvo2Text.length == 0)
{
//See if the move is a TM before proceeding
var tm = tmCheck(moveName);
if(!tm)
{
if(secondEvoText.length > 0)
{
babyMoveCell.css("color", evoColor);
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor); //highlights move name
}
else
{
babyMoveCell.css("color", prevoColor);
babyMoveCell.prev().find('a').eq(0).css("color", prevoColor);
}
}
}
}
else if(secondEvoText.length > 0)
{
if(hasFinalEvo1 && finalEvo1Text.length == 0 || hasFinalEvo2 && finalEvo2Text.length == 0)
{
var tm = tmCheck(moveName);
if(!tm)
{
secondEvoCell.css("color", evoColor);
babyMoveCell.prev().find('a').eq(0).css("color", evoColor);
}
}
}
}
});
function tmCheck(input)
{
var isTM = false;
//Iterate through TMmoves array to see if the input matches any entries
for(var i = 0; i < TMmoves.length; i++)
{
if(input == TMmoves[i])
{
isTM = true;
break;
}
}
if(isTM == true)
return true;
else
return false;
}
//alert("evoColor: " + localStorage.getItem('evoColor') + ". prevoColor: " + localStorage.getItem('prevoColor'))
}//end main()
// load jQuery and execute the main function
addJQuery(main);
This is the userscript I'm trying to implement this for. If anyone has any suggestions or ideas about why I'm getting the error, I'd love to hear them!
This does not work because, if you look carefully at what addJQuery does, you'll realize that it injects the code of the function you pass it into a script element that gets appended to the end of the body element.
This means that you're now working in the same space as the scripts the website has, so all GM_* are not going to be available. What you can do is to move some of the code which require those functions to outside the main function, but remember that the Greasemonkey sandbox means that code running inside the main function cannot communicate with code outside it directly. You can have indirect communication, through for example watching DOM manipulation, or even unsafeWindow, but looking at your code it does not appear to be easily separateable.
This approach will not work because addJQuery() is not transferring workspace objects to the page's scope, it's essentially recreating your code from the source.
That means that the GM_ functions are not usable because there is no link between the sandbox and the copy of the code that addJQuery() made.
If your script needs GM_ functions, then just use straight GM code with the // #require directive for things like jQuery. Your only option for Chrome is Tampermonkey.
In both cases, addJQuery()-like tricks are not needed.

Categories

Resources