• 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

    • Microsoft confirms Windows Outlook breaks in many ways after major Calendar feature upgrade by Sayan Sen Microsoft has been trying to get more users onto New Outlook for Windows, and it is doing so not just by enforcing the newer app but also by making improvements along the way. In doing so, though, the company has caused the Classic Outlook app to bug out in the past. The classic app received a major Shared Calendar-related upgrade recently, with many " long-awaited improvements" as well as "small changes in form and function." As the name suggests, the Outlook Shared Calendar essentially allows multiple people to interact with and manage the calendar. With Shared Calendar improvements enabled, users will see the following changes: Instant sync and view of shared calendars Editing series end date does not reset the past Accepting meeting without having to send a response Last Modified By no longer shown in the meeting item Adding same calendar multiple times can't be done Duplicate calendars simultaneously selection Attachments addition not possible when responding to a meeting invitation Event drafts auto-save changes The "Download shared folders" setting is ignored Unfortunately, as with any major feature upgrade, there are bugs, and Microsoft has confirmed this is no different. The tech giant has shared official guidance for it so that users can work around the problems. According to the company, "Shared Calendar improvements are now enabled by default in the most recent versions of Outlook, in all update channels for Microsoft 365 Apps," and thus, the bugs are likely to affect many. Here are some of the bugs Microsoft is investigating, as well as their workarounds: Bug Workaround Meeting cancellation sent unexpectedly to some attendees in classic Outlook In a REST shared calendar, after adding or removing an attendee, or forwarding a meeting, a meeting cancellation may be sent unexpectedly to some attendees. Use the Outlook Web App or new Outlook when adding or removing an attendee or forwarding a meeting. Attendees do not get updates on attachment changes by Delegate When a delegate sends an update on a meeting that requires removing an attachment on an occurrence of a meeting series, the recipients may not get some or all of the attachment changes. In the delegate's Sync Issues folder, you'll see sync errors. Example: 17:23:26 Synchronizer Version 16.0.15313 17:23:26 Synchronizing Mailbox 'Delegate User' 17:23:26 Synchronizing local changes in folder 'Manager User' 17:23:27 Uploading to server 'https://outlook.office365.com/mapi/emsmdb/?xxxxxxxx-xx' 17:23:30 Error synchronizing folder 17:23:30 [0-320] There is no known workaround. It is recommended, whenever possible, to save attachments to SharePoint or to OneDrive and share with a link. After an attachment is deleted from an existing meeting, it may reappear after being deleted Please wait approximately one minute to give the sync time to complete. Additionally, it is advisable to save attachments to SharePoint or OneDrive whenever possible and share them using a link. A meeting created by a delegate with limited calendar access disappears and is unsent when a sensitivity label other than "Normal" is selected Three potential solutions to address this issue, each with their own implications for functionality: Manager can update delegate's permissions to allow viewing of private items. Delegate can change the sensitivity label of the meeting to "Normal". Delegate can disable Shared Calendar Improvements (not recommended). Aside from these, Microsoft has also fixed several other bugs, which you can find in the official support article here on the company's website.
    • I’ve just paid £290/$390 for a 4TB Samsung 990 Pro for my PS5 Pro so it’s not too far from the going rate. Microsoft should definitely copy Sony and let users buy their own SSD in their next consoles rather than this proprietary stuff. I paid £374/$505 for the 2TB Seagate card for my Series X a few years ago so it’s not exactly over priced. 4TB of NVMe storage ain’t cheap!
    • The EU regulations force companies to respect users privacy, choice and data. Something all tech companies have abused to the hilt and would continue to do so if it wasn’t for important legislation and laws the EU brought in, which have been adopted elsewhere around the world. The EU can be a nuisance, but they actually do more good than harm. Forcing Apple, Google, Microsoft etc to make changes hasn’t negatively impacted anyone apart from their financials as they aren’t free to pillage our data like they once were, unless they explicitly provide options to obtain consent.
    • Windows 10 Enterprise IoT LTSC will continue getting updates until January 2032. I would expect support from most programs to continue until then. Firefox still supports Windows 7 (until the end of August), which will be just over 16 years since release. Windows 10 will be of a very similar age in January 2032. I'm sure some things like games will move on earlier, but I imagine a Windows 10 machine will be safe and usable for a long time to come yet, despite the pressure and fearmongering from those who stand to gain from selling you a new PC.
    • Refined dock and bug fixes land in latest Elementary OS 8 updates by David Uzondu If you're running Elementary OS 8, there's a new round of updates available, bringing some neat enhancements, particularly to its signature Dock and the underlying window manager, Gala. If you are not familiar, Elementary OS positions itself as a polished alternative to Windows and macOS. It runs its own custom desktop environment called Pantheon, with Gala handling all the window management magic, like animations and how windows behave. In the new update, the Dock gets some notable new tricks, including the return of a couple of features that old-school Plank (the Dock's foundation) users might remember. For starters, the Dock now shows multiple indicator dots beneath an app icon if you have more than one window open for that application, which is useful for quickly seeing what is running. Plus, if you are dragging something and hover over an app icon in the Dock, it will cycle through that app's open windows, making it easier to drop your item into the right place. You can also now long-press an app icon to bring up its context menu, a nice touch for those who prefer that interaction. The elementary OS team also squashed some bugs related to hide modes and memory usage, keeping things running smoothly. Gala itself recently got a massive update, addressing around 20 reported issues and introducing a brand new Gesture Controller. This means users can now swipe up in the Multitasking View to close windows, a slick and intuitive gesture. App titles are now always shown in Multitasking View, a significant improvement for touchscreen users. Users also get notified when they take a screenshot with a keyboard shortcut, and this notification lets them jump straight to the image in Files. Some other welcome Gala improvements include saving window states on sleep and shutdown, and fixing an annoying bug where menus might only show once. For gamers, a fix for Lutris Flatpak installations causing Gala to crash with GE Proton setups will be a relief, and users of the Postman app will be happy to know that window captures for it are no longer partially rendered. Shifting back to Elementary OS 8, in System Settings, choosing light or dark mode properly snoozes your schedule instead of outright disabling it. The Reduce Motion setting has been expanded to cover a wider array of animations, which is a blessing for folks prone to motion sickness. Hotcorners got some fixes too, and there is a new option to keep them active even when an application is full screen. Other notable updates include added screen reader support for notifications and the shortcut overlay, fixes for Flatpak sandbox issues that affected apps like Steam, and the latest version of GNOME Web, which brought better performance and a redesigned bookmarks sidebar. You can download all these updates by opening System Settings, heading to System, and hitting "Update All."
  • Recent Achievements

    • Enthusiast
      Epaminombas went up a rank
      Enthusiast
    • Posting Machine
      Fiza Ali earned a badge
      Posting Machine
    • One Year In
      WaynesWorld earned a badge
      One Year In
    • First Post
      chriskinney317 earned a badge
      First Post
    • Week One Done
      Nullun earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      186
    2. 2
      snowy owl
      131
    3. 3
      ATLien_0
      129
    4. 4
      Xenon
      121
    5. 5
      +Edouard
      91
  • Tell a friend

    Love Neowin? Tell a friend!