Javascript toggle list-style - javascript

I am trying to build a little toggle switch which removes line numbers on click.
I have got it working here: http://www.webdevout.net/test?09&raw
It is code highlighted by Geshi, and i build the javascript at the top to toggle line numbers.
This works fine, but what I would really want is that when the line numbers are 'hidden', that it also removes that gap on the left. So that the actual code fills the screen.
If clicked again, the lines numbers would come back again.

You have to change the ol element's padding to 0:
document.getElementsByTagName("ol")[0].style.padding = '0';
Above script is assuming you only have one <ol> in your document, or at least the first one is the one you'd like to edit.
EDIT
You would have to switch between
document.getElementsByTagName("ol")[0].style.paddingLeft = '20px';
and
document.getElementsByTagName("ol")[0].style.paddingLeft = '0px';
Your approach is a tad bit wrong though, you should be changing the listStyle of the <ol> tag and not of the individual <li> tags.
document.getElementsByTagName("ol")[0].style.listStyle = 'none';
and
document.getElementsByTagName("ol")[0].style.listStyle = 'decimal';
EDIT2 Perhaps give this a try. If you could also link me to it, I can test it in chrome and firefox as well. Maybe I'm not getting your problem..
function toggle_visibility() {
var e = document.getElementsByTagName("ol")[0];
if(e.style.listStyle == 'none') {
e.style.listStyle = 'decimal';
e.style.paddingLeft = '20px';
} else {
e.style.listStyle = 'none';
e.style.paddingLeft = '0px';
}
}
}
Link
<a onclick="toggle_visibility();">toggle</a>
EDIT3
Ah, I found the problem :)
if(document.getElementsByTagName("ol")[0].style.listStyle.substr(0,4) == 'none')
Because when you set the listStyle to 'none' it actually gets set to 'none outside none' by firefox and IE. So if you use .substr(0,4) to get the first 4 characters to compare to none, you should be fine :)

Related

Calling a value + style.display function?

I'm struggling to get this working because I don't know the right formatting.
What I am attempting is to get a CSS modal to display depending on what a user selects as a value in a Javascript applet.
The idea is to return .style.display = "block";
function onClick(event){
<something>.style.display = "block";
}
Where contains a value that has being saved in the format of intersects[0].object.title
So if for example I have selected "manhattan"
alert(intersects[0].object.title)
I'll get the string "manhattan" displaying correctly. That works perfectly.
But I can't get manhattan.style.display = "block"; returned and WORKING inside the function? I tried :
function onClick(event){
intersects[0].object.title.style.display = "block";
}
Also tried
function onClick(event){
(intersects[0].object.title).style.display = "block";
}
Any help would be greatly appreciated
This may not be directly what you're looking for, but it may help anyways. To make it work in your case, just change the button press to be a check for the selected value.
Rather than adjusting the CSS directly, this route modifies the element's classList to remove or add a .hidden class that contains the correct CSS.
// Loop through all modal buttons
document.querySelectorAll('.modal-button').forEach(function(element) {
// Add a click event listener to all modal buttons
element.addEventListener('click', function() {
// Toggle the target modal on click
toggleModal(element.dataset.target);
});
});
// Create the function to toggle the modals
function toggleModal(target) {
// Find the target
let targetElement = document.querySelector(target);
// Check if the target is hidden
if (targetElement.classList.contains('hidden')) {
// If it is, show it
targetElement.classList.remove('hidden');
} else {
// If it isn't, hide it
targetElement.classList.add('hidden');
}
}
.hidden {
display: none;
}
<button data-target="#modal" class="modal-button">Toggle Modal</button>
<div id="modal" class="hidden">Hey there, I'm a modal!</div>
I'm not certain from your question how the pieces of your puzzle are related to one another, and it would be helpful if you could clarify by showing more of your HTML and Javascript code, but I'll toss a couple of ideas at you in the meantime. Apologies if I'm telling you stuff you already know.
The only sort of object you would usually be able to set "style.display" on is an HTML element. To tell Javascript which HTML element you want to modify, you usually use a CSS selector like "document.getElementById('myDiv')"
It sounds like "manhattan" might be a piece of information you could use to uniquely identify the HTML element you intend to show. If so, there are four simple parts to showing the correct element:
associate the element with that particular string (eg via an id)
get the string at runtime (the same way as you did for the alert)
select the element based on the matching string
display the selected element
All together, it might look like this:
<div id="manhattan"></div>
<script>
var identifier = intersects[0].object.title;
alert(identifier) //I'm assuming this alerts "manhattan"
var elementToShow = document.getElementById(identifier);
elementToShow.style.display = "block";
</script>
Is this on the right track? If not, just provide more detail, and I'll see what else I can suggest.
Give to you div some id and then just change that:
<div id="test"></div>
document.getElementById("test").style["display"] = "block";
or
document.getElementById("test").style.display = "block";
or
document.getElementById("test").style.setProperty('display', 'block');
or
document.getElementById("test").setAttribute('display', 'block');

How to change CSS file or hide <link> tag

I want to change the design of my site by changing the CSS file attached. I have tried with script when the link is with id "link"
var x = document.getElementByID ("link")
X.href = style2
It didn't work.
The other thing I tried was to hide the <link> tag which had class "linkclass"
<style>
link.linkclass {
visibility:hidden;
}
</style>
But it didn't work either.
Can someone help.
Sorry if the code is bad formatted but I can't get how to format code in stack overflow
Three things wrong with this:
javascript is case sensitive. That means X is a different variable than x
style2 is not a valid URL. You have to use an URL to an existing .css file
<link> is not a visible element. Hiding an element that isn't visible in the first place accomplishes nothing.
This works:
var x = document.getElementByID("link");
x.href = "http://url/to/your/style2.css";
// ^ notice the lowercase x
If you wanna hide element (I got that impression from your examples), your javascript code should look like this:
var x = document.getElementById("link");
x.style.display = 'none';
Also take care with following:
-uppercase letters getElementbyId
-you're missing semicolon (;) after first expression
-your variable "x" is uppercase in second row("X").
In most cases this should be enough to disable element with CSS, just add this class (linkclass) to element which you want to hide:
<style>
.linkclass {
display: none;
}
</style>
You could do
$("#link").disabled = true;
This may also work.
document.getElementByID("link").disabled = true;
There is also another Stack question that addresses this here. Removing or Replacing a Stykesheet
update
You say you are trying to change the stylesheet. You could create a function to do it like this.
function styleSheetSwitcher( newFile ){
$("#link").prop("href", newFile);
}
styleSheetSwitcher("myNewCss.css");

Read more opens 1st one all the time

I've a page with about 10 short articles.
Each of them as a "Read More" button which when pressed displays hidden text
The issues I have at the moment is when I press the "Read More" on any of the 10 button it shows the 1st articles hidden content and not the selected one.
I think I need to set a unique ID to each article.. and the read more button be linked to it.. But I don't know how to set it.
I looked at this but couldn't get it working how to give a div tag a unique id using javascript
var WidgetContentHideDisplay = {
init:function() {
if ($('#content-display-hide').size() == 0) return;
$('.triggerable').click(function(e){
var element_id = $(this).attr('rel');
var element = $('#'+element_id);
element.toggle();
if (element.is(':visible')) {
$('.readmore').hide();
} else {
$('.readmore').show();
}
return false;
});
}
}
var div = documentElemnt("div");
div.id = "div_" + new Date().gettime().toString;
$(document).ready(function(){ WidgetContentHideDisplay.init(); });
OP Edit: Sorry, the original code wasn't in caps. I kept getting errors when trying to post, so I copied the code into Dreamweaver and it made it all caps for some reason.
Instead of selecting the element to toggle with an ID (i.e. $('#'+ELEMENT_ID)) you could setup a class for your item and use the class selection (e.g. $('.DETAILED-ARTICLE)') to select the child (or the brother, etc. depending how you built the HTML page).
In theory each ID should point to a single element but each class can be put to as many elements as you want.
If you're getting errors, read the errors and see what they are. Off of a quick read of your code, here are a couple things I noticed that will probably cause issues:
"documentElemnt" is misspelled, which will render it useless. Also, documentElement is a read-only property, not a function like you're using it.
toString is a function, not a property, without the parentheses (.toString()) it isn't going to function like you want it to.
Run the code, look at the errors in the console, and fix them. That's where you start.

Expanding/collapsing table rows while the text shortens/lengthens

I have, for example, 3 rows from a table. Each of the rows gets its content from a database. By default when the row is collapsed, the text should be shortened -
trs[i].innerText = trs[i].innerText.substring(0,25) + '...';
When a user clicks on the div it expands, and if clicked again - collapses.
if(tr.style.height == "150px")
{
tr.style.height = "20px";
}
else {
tr.style.height = "150px";
}
So far, so good, but I want the text to be shortened only if the div is collapsed. With my solution when the page loads the text is shortened, but when the row is expanded it remains shortened. How can I fix this? I can only think of when the row expands to call an AJAX function which returns the original data, but I don't think it's the best possible way. Thanks in advance.
First you'd have to store the full text before shortening it.
trs[i].fullText = trs[i].innerText;
trs[i].innerText = trs[i].innerText.substring(0,25) + '...';
Then you can restore it in the handler:
tr.innerText = tr.fullText;
tr.style.height = "150px";
Here's a jsFiddle. I'm using jQuery to select the elements, but you already have the correct tr's anyway. If you were using jQuery you could also use $(tr).data("fullText", $(tr).text()) which avoids some minor memory leaks with adding properties to DOM elements in old versions of Internet Explorer.

IE Javascript Clicking Issue

First off, I'm working on an app that's written such that some of your typical debugging tools can't be used (or at least I can't figure out how :).
JavaScript, html, etc are all "cooked" and encoded (I think; I'm a little fuzzy on how the process works) before being deployed, so I can't attach VS 2005 to ie, and firebug lite doesn't work well. Also, the interface is in frames (yuck), so some other tools don't work as well.
Firebug works great in Firefox, which isn't having this problem (nor is Safari), so I'm hoping someone might spot something "obviously" wrong with the way my code will play with IE. There's more information that can be given about its quirkiness, but let's start with this.
Basically, I have a function that "collapses" tables into their headers by making normal table rows not visible. I have "onclick='toggleDisplay("theTableElement", "theCollapseImageElement")'" in the <tr> tags, and tables start off with "class='closed'".
Single clicks collapse and expand tables in FF & Safari, but IE tables require multiple clicks (a seemingly arbitrary number between 1 and 5) to expand. Sometimes after initially getting "opened", the tables will expand and collapse with a single click for a little while, only to eventually revert to requiring multiple clicks. I can tell from what little I can see in Visual Studio that the function is actually being reached each time. Thanks in advance for any advice!
Here's the JS code:
bURL_RM_RID="some image prefix";
CLOSED_TBL="closed";
OPEN_TBL="open";
CLOSED_IMG= bURL_RM_RID+'166';
OPENED_IMG= bURL_RM_RID+'167';
//collapses/expands tbl (a table) and swaps out the image tblimg
function toggleDisplay(tbl, tblimg) {
var rowVisible;
var tblclass = tbl.getAttribute("class");
var tblRows = tbl.rows;
var img = tblimg;
//Are we expanding or collapsing the table?
if (tblclass == CLOSED_TBL) rowVisible = false;
else rowVisible = true;
for (i = 0; i < tblRows.length; i++) {
if (tblRows[i].className != "headerRow") {
tblRows[i].style.display = (rowVisible) ? "none" : "";
}
}
//set the collapse images to the correct state and swap the class name
rowVisible = !rowVisible;
if (rowVisible) {
img.setAttribute("src", CLOSED_IMG);
tbl.setAttribute("class",OPEN_TBL);
}
else {
img.setAttribute("src", OPENED_IMG);
tbl.setAttribute("class",CLOSED_TBL);
}
}
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Have you tried changing this line
tblRows[i].style.display = (rowVisible) ? "none" : "";
to something like
tblRows[i].style.display = (rowVisible) ? "none" : "table-row";
or
tblRows[i].style.display = (rowVisible) ? "none" : "auto";
setAttribute is unreliable in IE. It treats attribute access and object property access as the same thing, so because the DOM property for the 'class' attribute is called 'className', you would have to use that instead on IE.
This bug is fixed in the new IE8 beta, but it is easier simply to use the DOM Level 1 HTML property directly:
img.src= CLOSED_IMAGE;
tbl.className= OPEN_TBL;
You can also do the table folding in the stylesheet, which will be faster and will save you the bother of having to loop over the table rows in script:
table.closed tr { display: none; }
You might want to place your onclick call on the actual <tr> tag rather than the individual <th> tags. This way you have less JS in your HTML which will make it more maintainable.
If you enable script debugging in IE (Tools->Internet Options->Advanced) and put a 'debugger;' statement in the code, IE will automatically bring up Visual Studio when it hits the debugger statement.
I have had issues with this in IE. If I remember correctly, I needed to put an initial value for the "display" style, directly on the HTML as it was initially generated. For example:
<table>
<tr style="display:none"> ... </tr>
<tr style="display:"> ... </tr>
</table>
Then I could use JavaScript to change the style, the way you're doing it.
I always use style.display = "block" and style.display = "none"

Categories