• 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

    • I have tried that registry 'trick' from that video already. It doesn't work at all in Win11 for me   Yes it's a 3rd party app... that I am only using because of Microsoft breaking user customization in Windows 11. So yes... the is a Windows 11 issue. As of now to me, Microsoft has made a huge mistake with this in Windows 11.   The current font option in Windows 11 are terrible. They are just missing. People that want to use their own computer the way they want to, they need to avoid 11.
    • It's been an age since I did desktop support, but here goes: You have an issue with Windows 11, which is fair.  You are using a freeware 3rd party app to make modifications to the default Windows 11.  Since an update, this 3rd party application no longer plays nice with Windows 11.  And this is somehow Windows 11's fault? Sorry, not buying that this is a Windows 11 problem... it's a customization issue that has just appeared, but standard 3rd party support.   Clearly you're upset.  You can't make Windows do anything, just like you can't make MacOS run Explorer or Linux run Nintendo games natively.  And I know people are going to say "sure, it's possible..." but those aren't defining elements of the OS.  You can't have animated backgrounds in Windows 11 natively -- so it's trash amirite??? I did quick searches about changing the default fonts and there are ways to do it, and clearly 3rd party freeware apps can do it (basically my guess is they're making registry changes on your behalf) and clearly they're having issue.   You can make your computer do a lot of things, but sometimes you get what you pay for. Did a quick search and don't see an easy option in Windows 10 either.  Some of these links - ironically - are for Windows 10.  They still apply. Here's a video tutorial of how it can be done without a 3rd party:   Same reference here with a bit more detail: https://www.howtogeek.com/716407/how-to-change-the-default-system-font-on-windows-10/ Once the font is chosen, the size can be changed via personalization from my understanding. Hope this helps.
    • Videomass 5.0.26 by Razvan Serea Videomass is not just a common converter, it features file concatenation, time trimmer, ability to create thumbnails, tiled mosaics and animated giffs from movies; it has sophisticated GUIs for video filters, previews for video stabilization, resizing, croping, transposing, color equalization. It features PEAK, RMS and EBU audio normalization with streams indexing capabilities, a volume analyzer, audio preview and many more interesting features… For the people that are familiar with FFmpeg, it has a highly customizable preset manager with the possibility to easily make your own presets through the GUI and adapt this to your specific needs or create new presets using the FFmpeg command line. For less experienced people there are also ready-to-use presets. It offers out-of-the-box all possible file formats like MP4, M4V, M4A, MKV, AVI, OGV, WEBM, MP3, AC-3, WAV, OPUS, FLAC, OGG and encoders like MPEG-4, H.264/AVC, H.265/HEVC, VP8, VP9, LIBAOM-AVI, VORBIS, PCM, LAME, ALAC, etc. Also you can copy audio or video streams (lossless mode) without re-encoding, or extract audio from videos and much more! Main features No ads Multi-Platform, work on Linux, MacOs, Windows, FreeBsd. Batch processing. Queue management (only available for Presets Manager and A/V Conversions). Advanced log file management. Multi-panels, switch between panels using keyboard shortcuts. Audio/video processing using advanced tools and sophisticated filters interfaces. While downloading audio or video you can now do other transcoding tasks. Multi languages support (English, French, Italian, Russian, Dutch, Portuguese-BR, simplified Chinese, Spanish-ES, Spanish-CU, Spanish-MX) Conversions and transcoding Drag and drop to add multiple files simultaneously. Fully customizable presets and profiles. Possibility to create your new presets and profiles from scratch. Has useful presets to start with. Using the Presets Manager, you can set any format and codec supported by your FFmpeg build. Media file info (from FFprobe) and streams analyzer (from volumedetect). Shows the estimated time of arrival during encodings. Concatenate, merge media files losslessly. Create Slideshows. Extract images from video. Ability to switch between different FFmpeg builds. Has useful graphical tools for evaluating the supported features of a specific FFmpeg build. Audio stream mapping using selectable indexes. You can set both audio and video to copy when you just want to convert formats (lossless process). Timeline editor to slice time segments or trim the duration of your media even without re-encoding and therefore without loss of quality. It has GUI video filters such as: Resize Crop Transpose Deinterlace Denoise Stabilize Equalize Audio filters for volume normalization such us: PEAK, RMS and EBU-R128 normalizers. PEAK and RMS volume analysis reporting. Ability to select specified audio streams in videos to apply volume normalization. and much more… Videomass 5.0.26 changelog: Fixed yt-dlp preferences tab issue #372 Enabled import of the external «yt_dlp» package also on the standalone executable built by Pyinstaller. Improved handling of the yt-dlp executable (yt-dlp.exe on Windows) which now provides some automation and useful information for the users. Added «Whale» browser to the supported browser list for cookie automations. Update it_IT i18n, thanks to @bovirus Update zh_CN i18n, thanks to @userwljs Removed API functionality for download operations. Now only the yt-dlp executable is used for download operations. The API is still needed and will only be used for statistics extraction and format code listing. Fixed #374 Added «FLAC resampler» new preset. Notes: FFmpeg is not included in this archive. Before launching the application, ensure you have a compatible version of FFmpeg for your system architecture (requires ffmpeg.exe, ffprobe.exe, and ffplay.exe, version 5.1 or newer). For more details and downloads, visit: Gyan's FFmpeg builds page BtbN's FFmpeg GitHub releases page Antivirus False Positive Detection Some antivirus programs may mistakenly flag Videomass.exe as malicious. These are false positives. To resolve this, submit the Videomass.exe file to your antivirus vendor for further analysis and request a false positive review. Download: Videomass 5.0.26 | 18.4 MB (Open Source) Links: Videomass Home Page | Screenshots | Other OSes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      489
    2. 2
      +FloatingFatMan
      261
    3. 3
      snowy owl
      244
    4. 4
      ATLien_0
      222
    5. 5
      Edouard
      189
  • Tell a friend

    Love Neowin? Tell a friend!