• 0

Help needed in Javascript


Question

HI all I am having trouble getting a javascript to work as I want it.

The code is as follows:

function oc(a) {
	var o = {};

	for(var i=0;i<a.length;i++) {
		o[a[i]]='';
	}

	return o;

	// USE: if( name in oc(['bobby', 'sue','smith']) ) { ... }
}

function toggle() {
	var tagarray = document.getElementsByTagName("div");
	var padding = document.getElementById('padding');
	var arguments = arguments;

	for(var x=0; x<tagarray.length; x++) {
		var tagname = tagarray[x].getAttribute("id");

		if (tagname in oc(arguments) == true) {
			var tag = document.getElementById(tagname);

			if (tag.style.display == "") {
				tag.style.display = "none";
				padding.style.display = "";
			} else {
				tag.style.display = "";
				padding.style.display = "none";
			}
		} else {
			// tagname.style.display = "";
		}
	}

	for(var i=0; i<arguments.length; i++) {
		// alert(arguments[i]);
	}
}

the oc function is to search for a string in an array I found.

I want to call the script like this:

onclick="java script:toggle('products','content'); return false;"

The call is not restricted to how many items 1 or 10...

What it has to do is toggle the display css for a div to hide/show content. by using multiple names in the onclick I should be able to toggle 2 items at once.

Also to avoid conflict I would like the div id's to have an operating extension as in:

products_toggle == toggle

products_show == force display: ; if it isn;t already

products_hide == force display: none; if it isn;t already

I am going nuts on trying to get this to work. I have had it work half way there but not all features at once. The code above opens and closes the items but doesn't close all others that are open. each div will be a content panel and the reason for the multiple id's is so I can open a page panel and then show the relevant sub content on that page. For example I might call about_open, contact this should force open the about panel and show a contact form. the using about_open, privacy it should open about panel if not already and show the privacy content while closing all other div's.

If needed I can abbreviated each toggled div with a name as in id="about_content", id="contact_content" etc.

Please help me.

Link to comment
https://www.neowin.net/forum/topic/631537-help-needed-in-javascript/
Share on other sites

19 answers to this question

Recommended Posts

  • 0

var arguments = arguments;

What are you doing with that line?

You might be interested in jQuery, it is a javascript framework which augments the standard javascript objects with additional ones, so you could probably achieve the above effect in much fewer lines:

function toggle() {
	for (int i = 0; i < arguments.length; i++) {
		$(arguments[i]).toggle();
	}
}

You should be able to call it simply with: toggle("first", "second", "third"); etc.

  • 0

Sorry to be a pain but I don't think I want to use jQuery for just one script. if I was going to use more scripts I would.

The

var arguments = arguments;

is what I have read I must do. arguments is the array of items from the function call, and I have to declare it. I wanted the arguments array to be called arguments.

If its wrong fix it. Im no javascirpt expert. in fact this is the first time I have actually written anything in javascript.

  • 0

jQuery will become very useful if you plan to go into full Web 2.0 development (which according to your other thread, it is planned).

Remove this

var arguments = arguments;

as it is not required, and may be causing your browser to abort the script

  • 0

It may not be required but its definetly not aborting the script. As I said before it works, partly.

And your reading my other post? Got any thoughts about that?

My main issue is not only am I a perfectionist, I believe in opensource and accesability (ie API, plugins etc for customization and integration), I also hate writing the same code over and over again, and I like simple clean minimalistic code. I also would like to write using standards as in standard code, formatting, structure etc. for example if I am doing a menu in a web page I'll use a list. hey I even made an accordion style website once using ONLY <ul>. Never used it just did it to see if I can get the structure to work as <ul> not <div>.

So any help on that would be handy. The script above is also not for the site on the other post. thats a different thing all together.

  • 0

Well, a non-jQuery function could work as follows:

function toggle() {
	for (var i = 0; i &lt; arguments.length; i++) {
		var obj = document.getElementById(arguments[i]);
		obj.style.display = (obj.style.display == "none") ? "block" : "none";
	}
}

Called as "java script: toggle('one', 'two', 'three');".

I have attached an example html document.

test.htmlFetching info...

  • 0

Sorry to be a pain, but there is not consistancy with your test page. click randomly on the links and the same links give different results.

The link to the page I am going to use it on is here: http://eangulus.homeip.net/clients/eangulu....com/index6.php

On my design there is also a div id="padding" that has to be hidden whenever one of the pages is open. Only one page to be open at a time. but the submenu content in each page is the reason for the multiple id need. this way I can use the toggle in a similar fashion for the sub links to change between contetn. and then I can call for example aboutus, will opn aboutus div with about us contetn as default, but click on contact in the bottom footer and it should open aboutus and show the contact form div instead.

At this stage I have each content area id's and the padding id and also the sample contetn under products has the id="content". THere will be more but I have put in enough for testing.

Anyway going to bed now so I will talk in the morning.

  • 0

OK I understand now what your code does.

But I do have some more questions.

How can I search for all elements with an id ending in "_toggle" and have that in an array, then I should be able to go thru each array element and match against the arguments. If it doesn't match close the tag, if it does I want to then search for the ending of the called tag (_open _close or _swap etc) and either open or close according to that answer.

  • 0

Well, unless your planning to increase the number of expanding sections, you could probably get away with an array based function:

function open(id) {
	var layers = ['one','two','three','four','five'];
	for (var i = 0; i &lt; layers.length; i++) {
		var obj = document.getElementById(layers[i]);
		if (obj) {
			if (layers[i] == id) 
				obj.style.display = "block";
			else
				obj.style.display = "none";
		}						
	}
}

  • 0

Ok, final version:

function open(parent, child) {
	var parents = ['one', 'two'];
	for (var i = 0; i &lt; parents.length; i++) {					
		var parentObj = document.getElementById(parents[i]);
		if (parentObj) {
			if (parents[i] == parent) 
				parentObj.style.display = "block";
			else
				parentObj.style.display = "none";
		}	
	}

	var children = document.getElementsByTagName("div");
	for (var j = 0; j &lt; children.length; j++) {
		if (children[j].id.indexOf("_child") &gt; 0) {
			var childId = child + "_child";
			if (children[j].id == childId)
				children[j].style.display = "block";
			else
				children[j].style.display = "none";
		}
	}
}

With an attachment:test.html

  • 0

LOL, you've been watching my page.....

Thank you so much for that last script. Have another look, its working as I want it too now, (only first 2 links under products are setup atm). I also add in the padding.

I know it was getting complicated but I was trying to learn javascript, and I was really only converting the steps in my head to paper so to speak.

Oh and I apologize. the script samples always worked, it was my practice code that was cause the crash. as soon as I deleted all my stuff it work a treat.

Sorry to be a pain in the ass, but is it hard to make the parent items toggle? If it is don't worry cause I was looking at dropping that feature anyway.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Plasma 6.5 brings improved Emoji Selector, better performance in Activity manager, and more by David Uzondu This week saw the long-awaited release of KDE Plasma 6.4, bringing better window management and a whole lot of color management features. Apart from the release of 6.4, the KDE team was able to get other work done, and this was all outlined in the latest issue of This Week in Plasma, which details what is coming down the pipe for future versions. Looking ahead to Plasma 6.5, the developers are making some notable changes to improve performance and general usability. To prevent its database from growing endlessly and causing performance problems over time, the Activity Manager service will now only store the last four months of your history by default. The Emoji selector app is also getting a much-needed redesign that makes the window more compact and moves the sidebar button to the header for a cleaner look. Other little details for 6.5 are being polished up too. The unpopular vertical line separating the date and time on the horizontal Digital Clock widget is gone; if you want it back, you can add it yourself with a custom date format. The "Add New" button has also been moved to the top toolbar in the Shortcuts page within Settings, freeing up some valuable screen real estate. The devs also reduced the minimum size of custom tiling tiles, a small but significant fix for anyone with an ultrawide monitor. In addition to that, the Networks widget's captive portal banner now uses inline header styling, so it doesn't look like a bunch of frames stacked inside each other anymore. Of course, before we get to 6.5, the current release needs some attention. Plasma 6.4's first bug fix release, 6.4.1, addresses issues like broken item selection in the Folder View widget and a bug that could cause the system to lock or suspend faster than intended. Keyboard navigation in list views in Discover feels smoother now, and text is easier to read in certain list items in KRunner. The devs also cleaned up how list items look when you press or click them in Discover. 6.4.1 also fixes a bug where the clipboard history popup would fail to select the top item, and makes the Earth Science Picture of The Day wallpaper plugin work again after its data source changed. Here's the full list of fixes: Fixed several issues in the Folder View widget that caused selecting or opening items to not work when using certain non-default view settings, when the view was scrollable, or when using a touchscreen. Fixed a bug in the Meta+V clipboard popup that sometimes failed to pre-select the top-most item. The Clipboard settings window’s shortcuts page no longer shows columns for local shortcuts that don’t do anything, since the clipboard is global in scope. Fixed the Earth Science Picture of the Day wallpaper plugin after the source data changed formatting again. Made a few fixes to the “Missing Backends” section of Discover’s settings window that kept it from working properly. Fixed a bug that prevented direct scan-out (and its performance benefits) from activating on rotated screens. Fixed an issue where the system could lock or suspend sooner than expected after an app stopped blocking those actions. Installing a new wallpaper plugin no longer causes the plugin list combobox to appear blank. The team even went back to squash some bugs in the older 6.3.6, tackling an issue that could cause keyboard shortcuts to get lost during a system upgrade and fixing an overflow bug with KRunner's faded completion text. Plasma 6.4.1 is set to arrive on June 24th, with 6.3.6 following on July 8th.
    • UniGetUI 3.2.1 Beta 1 by Razvan Serea UniGetUI is an application whose main goal is to create an intuitive GUI for the most common CLI package managers for Windows 10 and Windows 11, such as Winget, Scoop and Chocolatey. With UniGetUI, you'll be able to download, install, update and uninstall any software that's published on the supported package managers — and so much more. UniGetUI features Install, update and remove software from your system easily at one click: UniGetUI combines the packages from the most used package managers for windows: WinGet, Chocolatey, Scoop, Pip, Npm and .NET Tool. Discover new packages and filter them to easily find the package you want. View detailed metadata about any package before installing it. Get the direct download URL or the name of the publisher, as well as the size of the download. Easily bulk-install, update or uninstall multiple packages at once selecting multiple packages before performing an operation Automatically update packages, or be notified when updates become available. Skip versions or completely ignore updates in a per-package basis. Manage your available updates at the touch of a button from the Widgets pane or from Dev Home pane with UniGetUI Widgets. The system tray icon will also show the available updates and installed package, to efficiently update a program or remove a package from your system. Easily customize how and where packages are installed. Select different installation options and switches for each package. Install an older version or force to install a 32bit architecture. [But don't worry, those options will be saved for future updates for this package] Share packages with your friends to show them off that program you found. Here is an example: Hey @friend, Check out this program! Export custom lists of packages to then import them to another machine and install those packages with previously-specified, custom installation parameters. Setting up machines or configuring a specific software setup has never been easier. Backup your packages to a local file to easily recover your setup in a matter of seconds when migrating to a new machine UniGetUI 3.2.1 Beta 1 changelog: Added per-package-manager default install options Added the ability to run pre-install/update/uninstall and post-install/update/uninstall commands Added the ability to kill process(es) before a package is installed/updated/uninstalled Block custom command-line arguments (and pre/post commands) behind a SecureSetting switch SecureSettings are settings that require administrator privileges to be switched. Bundles won't import custom arguments & custom commands by default Bundles will show a security report when importing potentially dangerous settings Added a better crash message for when UniGetUI files are missing Deep improvements to how bundles and InstallOptions are loaded from disk. Improvements to WebView lifecycle Download: UniGetUI 3.2.1 Beta 1 | 51.7 MB (Open Source) Links: WingetUI Home Page | GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I'm just waiting on what they will do when outlook doesn't load properly, and you have to set a new profile as a test.
    • Weekend PC Game Deals: Rhythm bundles, fishing festivals, and DRM-free summer sales by Pulasthi Ariyasinghe Weekend PC Game Deals is where the hottest gaming deals from all over the internet are gathered into one place every week for your consumption. So kick back, relax, and hold on to your wallets. The Humble Store introduced the June Tunes collection this week. Coming in with music and rhythm titles, the bundle begins with Wanderson, Everhood, and Onde in the first tier for $5. Going up a tier by paying $8 gets you three more games: Rhythm Fighter, One Btn Bosses, and Oddada. Lastly, Trombone Champ, DJMAX RESPECT V, and Ragnarock lead the final tier, which are yours for $10. Just yesterday, Humble also brought out the Serenity Forge Storyteller's Bundle. This carries 12 indie games inside it, including LISA the Joyful and LISA the Painful, Neversong, Death's Gambit, Smile for Me, Long Gone Days, and more, all split into three tiers of prices. Replacing Two Point Hospital, The Operator landed as the latest freebie on the Epic Games Store earlier this week. The 2024-released indie title has you taking the role of a new hire at the Federal Department of Intelligence (FDI). Here you have to analyze evidence, fact-check, and try to solve a streak of mysterious crimes using the agency's advanced investigative software. However, as the story progresses, a conspiracy is revealed that paints the FDI in a different light. The Operator giveaway on the Epic Games Store is slated to last until June 26. On the same day, Sable will become the next freebie in the promotion. Free Events If you're looking to try out some games over the weekend without opening your wallet, there are three games having free weekend offers right now. Starting off, Paradox is offering its grand strategy experience, Victoria 3, to try out. The title has a much higher focus on state management than war and roleplaying compared to the company's other games. If that's too much of a tough start, Len's Island is temporarily free-to-play now too. This is a top-down perspective survival game with support for up to eight players in co-op, with combat, farming, dungeon diving, and other elements being included. Lastly, Dead by Daylight should be the most familiar to most. The multiplayer four-versus-one asymmetric survival horror game has you assuming the roles of survivors or the killer to see who can come out on top. Big Deals With the Steam Summer Sale only being days away, most publishers and developers are laying low to prepare for the big event. Still, we found quite a few games having some attractive discounts. Here's our hand-picked big deals list for this weekend: Red Dead Redemption – $29.99 on Steam Mount & Blade II: Bannerlord – $24.99 on Steam Timberborn – $24.49 on Steam BERSERK and the Band of the Hawk – $23.99 on Steam Wo Long: Fallen Dynasty – $23.99 on Steam Disney Epic Mickey: Rebrushed – $23.99 on Steam Jagged Alliance 3 – $22.49 on Steam [NINJA GAIDEN: Master Collection] NINJA GAIDEN Σ2 – $19.99 on Steam Alone in the Dark – $19.99 on Steam Last Train Home – $19.99 on Steam Len's Island – $19.49 on Steam Nightingale – $17.99 on Steam DYNASTY WARRIORS 8: Xtreme Legends Complete Edition – $16.99 on Steam Mortal Kombat 1 – $16.49 on Steam SOMA – $14.99 on Steam Victoria 3 – $14.99 on Steam Trepang2 – $14.99 on Steam Blasphemous 2 – $14.99 on Steam Wreckfest – $14.99 on Steam Expeditions: Rome – $14.84 on Steam EA SPORTS FC 25 – $13.99 on Steam STAR WARS Jedi: Survivor – $13.99 on Steam DRAGON BALL Z: KAKAROT – $12.99 on Gamesplanet Amnesia: The Bunker – $12.49 on Steam DREDGE – $12.49 on Steam Dead Space – $11.99 on Steam DAVE THE DIVER – $11.99 on Steam WILD HEARTS – $10.49 on Steam It Takes Two – $9.99 on Steam Dragon Age Inquisition – $9.99 on Steam Haven – $9.99 on Steam Hellboy Web of Wyrd – $9.99 on Steam Nova Lands – $9.99 on Steam BIOMUTANT – $9.99 on Steam Destroy All Humans! 2 - Reprobed – $9.99 on Steam Ghostrunner 2 – $9.99 on Steam Need for Speed Unbound – $9.79 on Steam Call of the Wild: The Angler – $8.99 on Steam DEAD OR ALIVE 6 – $8.99 on Steam Operation: Tango – $8.99 on Steam Katana ZERO – $8.99 on Steam Dead by Daylight – $7.99 on Steam Killer Frequency – $7.49 on Steam Nioh: Complete Edition – $7.49 on Steam Overcooked! 2 – $6.24 on Steam A Way Out – $5.99 on Steam Mass Effect Legendary Edition – $5.99 on Steam Darksiders Genesis – $5.99 on Steam Mortal Kombat 11 – $4.99 on Steam Titanfall 2 – $4.49 on Steam Golf With Your Friends – $4.49 on Steam STAR WARS Battlefront II – $3.99 on Steam Yoku's Island Express – $3.99 on Steam theHunter: Call of the Wild – $3.99 on Steam RoboCop: Rogue City – $3.74 on Fanatical Battlefield 2042 – $2.99 on Steam Road Redemption – $2.99 on Steam Shadow Warrior 2 – $2.99 on Steam Battlefield V – $2.49 on Steam Ultimate Fishing Simulator – $1.99 on Steam DRM-free Specials The GOG store has already kicked off its own summer sale, putting thousands of DRM-free games on sale. Here are some highlights: Cyberpunk 2077 - $23.99 on GOG God of War - $19.99 on GOG Fallout 4: Game of the Year Edition - $15.99 on GOG Fallout 4: Game of the Year Edition - $15.99 on GOG Dino Crisis Bundle - $15.29 on GOG Devil May Cry HD Collection & 4SE Bundle - $14.84 on GOG The Witcher 3: Wild Hunt - Complete Edition - $9.99 on GOG Vampire: The Masquerade - Bloodlines - $9.99 on GOG SPORE Collection - $7.49 on GOG Papers, Please - $4.99 on GOG Terraria - $4.99 on GOG SWAT 4: Gold Edition - $4.99 on GOG DOOM (2016) - $3.99 on GOG DOOM 3 - $3.99 on GOG CrossCode - $3.99 on GOG Mad Max - $2.99 on GOG Heroes of Might and Magic 3: Complete - $2.49 on GOG Heroes of Might and Magic 4: Complete - $2.49 on GOG World in Conflict: Complete Edition - $2.49 on GOG Alan Wake - $1.49 on GOG Mortal Kombat 1+2+3 - $1.49 on GOG RollerCoaster Tycoon Deluxe - $1.19 on GOG Keep in mind that availability and pricing for some deals could vary depending on the region. That's it for our pick of this weekend's PC game deals, and hopefully, some of you have enough self-restraint not to keep adding to your ever-growing backlogs. As always, there are an enormous number of other deals ready and waiting all over the interwebs, as well as on services you may already subscribe to if you comb through them, so keep your eyes open for those, and have a great weekend.
    • Is there a 'recovery' settings option in Settings? The one where we can rollback to a previous restore point. I find it very useful if there is some issue and I have to rollback to the last stable point.
  • Recent Achievements

    • Contributor
      GravityDead went up a rank
      Contributor
    • Week One Done
      BlakeBringer earned a badge
      Week One Done
    • Week One Done
      Helen Shafer earned a badge
      Week One Done
    • First Post
      emptyother earned a badge
      First Post
    • Week One Done
      Crunchy6 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      666
    2. 2
      ATLien_0
      269
    3. 3
      Michael Scrip
      237
    4. 4
      Steven P.
      165
    5. 5
      +FloatingFatMan
      155
  • Tell a friend

    Love Neowin? Tell a friend!