• 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

    • Staged. It's a requirement that vehicles are strapped down to the bed. Usually wheel and/or chassis tie downs are used. That appears to just be on the winch.
    • I feel Apple's big problem is the lack of big data to train any AI LLM model. They have statistics on usage, but they don't have the written social media, messaging (they were early adopters of end-to-end encryption), they didn't scrape the Internet before the book companies and new sources were wise. So they have no choice but to use a third party LLM provider. Which ties them in knots with their own stance on security and privacy. In short, they are royally stuffed when it comes to developing an in-house AI.
    • Nothing is black and white. Democracy can suck, just as communism can. The risk is people who blindly think one is vastly superior over the other. Democracy needs a lot to make it work well, and there are many examples around the world of it. Good education, mandatory voting, accessible voting, and removing money from politics are just a few elements that need to be sorted for a functional democracy. The USA is the playbook on what not to do with democracy.
    • Weekend PC Game Deals: Showcase specials, Timeloop freebies, Resident Evils, and more 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 Epic Games Store brought the finale of its Mega Sale mystery giveaways this week, and that involved giving away the Bethesda and Arkane title Deathloop alongside the indie title Ogu and the Secret Forest. Deathloop comes in as a time-loop FPS adventure that puts you into the shoes of an assassin that must take down eight targets in a single day to escape the time travel shenanigans. In usual Arkane fashion, each target can be taken care of in multiple ways, and there are supernatural powers that give the player upgrades like teleportation and telekinesis. There is an invasion mechanic for taking down other players in their campaigns too. As for Ogu and the Secret Forest, it's an indie adventure featuring hand-drawn characters and intricate puzzles. The 2D game involves befriending characters across a fantasy land as baby Ogu, with plenty of exploration elements and boss battles available. The Deathloop and Ogu and the Secret Forest giveaways are available on the Epic Games Store until June 12. On the same day, the store will begin a giveaway for the humorous hospital simulation entry Two Point Hospital. Next, we look at a giveaway happening on the Steam store. Gearbox is only a few months away from releasing Borderlands 4, and to prepare some new fans, Borderlands 2 is free to claim on Steam right now. The four-player cooperative title offers a humorous campaign filled with wacky villains, a massive amount of weapons to loot, and skill trees that let you break the balance entirely. The Borderlands 2 giveaway on Steam is live right now. It's slated to come to an end on June 8 at 10am PT. Since it's a new month, the Humble Choice bundle went through its standard refresh earlier this week, releasing eight more games for subscription holders to add to their library. This time, you can grab Warhammer 40K: Boltgun, Legacy of Kain Soul Reaver 1 and 2 Remastered, Nobody Wants to Die, Dungeons of Hinterberg, Tchia, Sker Ritual, Biped, and Havendock. It will cost you $12 to get all eight games. As a month-long Humble Choice Bundle, though, you can ponder the contents until July 1, when a new selection of games will replace these ones. In the regular bundle space, the Humble Store is also celebrating showcase season with its IGN Live bundle. This carries Slay the Spire, Potion Craft: Alchemist Simulator, and Bloodroots in the starting tier for $10. Next, paying $16 gets you copies of Art of Rally, Old World, and Black Book. Lastly, paying the full $22 for the bundle will add on copies of The Medium and Wartales. The bundle has a two-week counter attached to it, so you have plenty of time to decide on it. Big Deals Alongside plenty of showcase-related sales, massive franchise discounts from 2K, Capcom, Techland, and more are currently available for you to check out. Here are our hand-picked big deals for this weekend: Lies of P – $29.99 on Steam Company of Heroes 3 – $29.99 on Steam Sekiro: Shadows Die Twice - GOTY Edition – $29.99 on Steam Dragon's Dogma 2 – $29.39 on Steam Satisfactory – $27.99 on Steam Diablo IV – $27.49 on Steam Another Crab's Treasure – $20.99 on Steam Resident Evil 4 – $19.99 on Steam Tetris Effect: Connected – $19.99 on Steam Dying Light 2 Stay Human: Reloaded Edition – $19.79 on Steam No Man's Sky – $19.62 on Gamebillet Chained Echoes – $18.74 on Steam Starship Troopers: Terran Command – $17.99 on Steam The Outlast Trials – $15.99 on Steam Tales from the Borderlands – $14.99 on Steam Phasmophobia – $14.99 on Steam Divinity: Original Sin 2 - Definitive Edition – $13.49 on Steam Gotham Knights – $11.99 on Steam Receiver 2 – $9.99 on Steam Resident Evil Village – $9.99 on Steam Goat Simulator 3 – $9.89 on Steam Borderlands Game of the Year Enhanced – $9.89 on Steam The Outer Worlds – $9.89 on Steam Dorfromantik – $9.79 on Steam Turnip Boy Robs a Bank – $9.74 on Steam Ni no Kuni II: Revenant Kingdom – $9.59 on Steam Batman: Arkham Collection – $8.99 on Steam Escape Academy – $8.00 on Steam Resident Evil 7 Biohazard – $7.99 on Steam Inscryption – $7.99 on Steam Devil May Cry 5 – $7.49 on Steam Watch_Dogs 2 – $7.49 on Steam Suicide Squad: Kill the Justice League – $6.99 on Steam Control Ultimate Edition – $5.99 on Steam Injustice 2 Legendary Edition – $5.99 on Steam Manifold Garden – $4.99 on Steam Cultist Simulator – $4.99 on Steam Watch_Dogs – $4.99 on Steam Dragon's Dogma: Dark Arisen – $4.79 on Steam ARK: Survival Evolved – $4.49 on Steam Batman: Arkham Origins – $3.99 on Steam Dying Light – $3.99 on Steam PAYDAY 2 – $3.29 on Steam WRC 9 FIA World Rally Championship – $2.99 on Steam Alan Wake – $2.99 on Steam Borderlands 3 – $2.99 on Steam Among Us – $2.99 on Steam Hitman: Absolution – $1.99 on Steam Borderlands 2 – $0 on Steam Ogu and the Secret Forest – $0 on Epic Store Deathloop – $0 on Epic Store DRM-free Specials The GOG store's latest DRM-free specials for this weekend are touting Atari classics, story-rich games, and much more. Here are some highlights: Atari 50: The Anniversary Celebration - $19.99 on GOG The Thaumaturge - $19.24 on GOG Turok 3: Shadow of Oblivion Remastered - $17.99 on GOG STAR WARS: Dark Forces Remaster - $16.49 on GOG INDIKA - $16.24 on GOG Blood West - $12.49 on GOG Shadowrun Trilogy - $10.07 on GOG Disco Elysium - The Final Cut - $9.99 on GOG Pathologic 2 - $6.99 on GOG Tacoma - $6.59 on GOG Little Nightmares - $4.99 on GOG RollerCoaster Tycoon 3: Complete Edition - $4.99 on GOG Gone Home - $4.94 on GOG Blade Runner - Enhanced Edition - $2.49 on GOG Blood: Fresh Supply - $2.49 on GOG SiN Gold - $1.99 on GOG The Wheel of Time - $1.49 on GOG RollerCoaster Tycoon Deluxe - $1.19 on GOG Pirates! Gold Plus - $1.19 on GOG Sid Meier's Colonization - $1.19 on GOG POSTAL 2 - $0.99 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.
    • I too am left of centre in my politics, and not from the USA. But to understand what enables this sort of wealth means you have to understand the American mentality and generational politics, and what that means. My point was that its sort of ironic that he's giving away much if it to another country, because of the prevalence of individualism and tax system in the USA. People who subscribe to that are probably the ones shocked that he's giving away his wealth, as they're the ones who say "you can do whatever you want to with your money!"
  • Recent Achievements

    • 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
    • Week One Done
      daelos earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      489
    2. 2
      snowy owl
      255
    3. 3
      +FloatingFatMan
      250
    4. 4
      ATLien_0
      223
    5. 5
      +Edouard
      187
  • Tell a friend

    Love Neowin? Tell a friend!