1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Viewport problems with javascript

Discussion in 'JavaScript' started by MichHenr, Aug 7, 2017.

  1. #1
    Hi

    I'm having a problem I simply can't find the solution for... I hope someone here can help..

    On my website I have the meta tag in my header:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    In my stylesheet I use the viewport sizes like width: 40vw and font-size: 3vw etc when a phone or tablet is in portrait, and it works perfectly..

    But... I have a search field that calls a php file with the search result like this:
    onkeyup="Search(this.value, 'visdiv', 'Wait while the system works');"
    SEMrush
    And it is shown in a <div> like this:
    <div id="visdiv"></div>

    The problem is that the php file it opens in the visdiv doesn't have a header, and therefore the viewport sizes doesn't seem to work on that php file... So I can't set the font-size or the width of that search window by viewport sizes in my stylesheet...
    Is there any way to do this?


    The javascript that gets the php file is this one:
    function Search(Searchword, sideElement, kaldMessage) {
    document.getElementById(sideElement).innerWidth = kaldMessage;
    try {
    req = new XMLHttpRequest(); /* f.eks. Firefox */
    } catch(e) {
    try {
    req = new ActiveXObject("Msxml2.XMLHTTP"); /* IE-versioner */
    } catch (e) {
    try {
    req = new ActiveXObject("Microsoft.XMLHTTP"); /* IE-versioner */
    } catch (e) {
    req = false;
    }
    }
    }
    req.onreadystatechange = function() {SvarSearch(sideElement);};
    req.open("GET","SearchResult.php" + "?searchword=" + Searchword,true);
    req.send(null);
    }

    function SvarSearch(sideElement) {
    var output = '';
    if(req.readyState == 4) {
    if(req.status == 200) {
    output = req.responseText;
    document.getElementById(sideElement).innerWidth = output;
    }
    }
    }

    The website this is on is this one, with the search field in the top: www.danskefilmstemmer.dk


    Hope someone can help me...

    Best
    Michael
     
    MichHenr, Aug 7, 2017 IP
    SEMrush
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,410
    Likes Received:
    1,504
    Best Answers:
    220
    Trophy Points:
    515
    #2
    Why would an input HAVE a DIV around it? Why would ANYTHING in your scripting be effected by the viewport META? Why would your layout (something CSS should be exclusively be controlling) have ANYTHING to do with your scripting?

    Why the HELL would you have a 40 times the view width in your CSS, much less a font-size based on view width? Are you just TRYING to piss off visitors?!?

    LOOKING at your site, do the world a favor and back AWAY from the scripttardery and bother learning to use HTML properly FIRST. You may also want to learn what a legible colour contrast is, since white on green isn't it. Tables for layout? What is this 1997?

    You've got tables for nothing, tables for layout, little to no separation of presentation from content, nothing remotely resembling semantic markup (aka using HTML properly) -- I'm half shocked it's not a tranny document given that the code is clearly in 'transition' from 1997 to 1998 development practices.

    OF COURSE you're having layout problems. CSS and layout are only as good as the HTML they are applied to -- and your HTML looks like it was slopped together any-old-way in a WYSIWYG.

    Gets worse in the meta -- meta no legitimate UA uses, conflicting meta, values in things like robots that don't even EXIST... charset meta too far down the document (should be FIRST THING after you open <head>), HTML 3.2 formatting in your 4 strict document (upper case == invalid), blocking scripttardery inside <head>... broken advert scripting that doesn't even run here in a spot where you should NEVER place an advert. (before you even open the page's H1? REALLY?!?)

    If your HTML were well formed and properly written, there is NO reason for it to be more than:

    <!DOCTYPE html><html lang="da-dk"><head><meta charset="utf-8">
    <meta
    	name="viewport"
    	content="width=device-width,height=device-height,initial-scale=1"
    >
    <meta
    	name="description"
    	content="Klik dig rundt i vores kæmpe database om danske stemmer på film, tegnefilm, serier og lign."
    >
    <link
    	rel="shortcut icon"
    	href="favicon.ico
    >
    <link
    	rel="stylesheet"
    	href="screen.css"
    	media="screen,projection,tv"
    >
    ><!-- HTML 5 validation kvetches about projection,tv **** that noise! -->
    <title>
    	Danske Film Stemmer - DanskeFilmStemmer.dk
    </title>
    </head><body>
    
    <h1><a href="/">DANSKE FILM STEMMER .dk</a></h1>
    
    <div id="top">
    	
    	<ul id="mainMenu">
    		<li><a href="ListeP.php">Personer</a></li>
    		<li><a href="ListeF.php">Film/Serier</a></li>
    		<li><a href="ListeK.php">Karakterer</a></li>
    		<li><a href="ListeS.php">Studier</a></li>
    	</ul>
    	 
    	<div id="searchAndSocial">
    	
    		<input type="checkbox" id="showHideWhyTheHellIsThisNotInTheMenu">
    		<label for="showHideWhyTheHellIsThisNotInTheMenu"></label>
    		<ul id="whyTheHellIsThisNotInTheMenu">
    			<li><a href="Om.php">Om</a></li>
    			<li><a href="Statistik.php">Statistik</a></li>
    			<li><a href="Seneste.php">Seneste tilføjelser</a></li>
    			<li><a href="InfoViMangler.php">Info vi mangler</a></li>
    		</ul>
    		
    		<ul id="socialMenu">
    			<li>
    				<a href="https://www.facebook.com/danskefilmstemmer" >
    					<img src="Grafik/LinkFacebook.png" alt="facebook">
    				</a>
    			</li><li>
    				<a href="https://www.facebook.com/groups/444196592646079/">
    					<img src="Grafik/LinkGroup.png" alt="Facebook Gruppe">
    				</a>
    			</li><li>
    				<a href="mailto:mail@danskefilmstemmer.dk">
    					<img src="Grafik/LinkMail.png" alt="Kontakt">
    				</a>
    			</li>
    		</ul>
    		
    		<iframe
    			src="https://www.facebook.com/plugins/share_button.php?href=http%3A%2F%2Fdanskefilmstemmer.dk%2Findex.php%3F&layout=button&size=small&mobile_iframe=true&width=59&height=20"
    			width="59" height="20"
    			scrolling="no"
    			frameborder="0"
    			allowTransparency="true"
    			class="fbShare"
    		></iframe>
    		
    		<form method="post" action='' id="searchForm">
    			<fieldset>
    				<label for="searchField">Søg:</label>
    				<input type="text" id="searchfield" name="searchfield" size="35">
    				<!--
    					your script should hook the element by ID, not be crapped into
    					the markup with onEvent attributes that can be DISABLED by things
    					like the "Content Security Policy"!
    				-->
    			</fieldset>
    		</form>
    		
    	<!-- #searchAndSocial --></div>
    	
    	<div id="content">
    		<h2>Halløj allesammen :)</h2>
    		<img
    			src="Grafik/MickeyWelcome.png"
    			alt="Mickey Says Welcome"
    			class="plate"
    		>
    		<!--
    			Don't manually space yer bloody content with breaks, you want
    			it narrower, narrow the P from the stylesheet!
    			
    			These are grammatical paragraphs, not just text slopped in with double-breaks!
    		-->
    		<p>
    			Velkommen til DanskeFilmStemmer.dk
    		</p><p>
    			Her på siden kan du browse rundt i en mega database, og finde ud af hvem der har lagt dansk stemme til de forskellige karakterer i tegnefilm, børnefilm og serier igennem tiden.
    		</p><p>
    			Brug menu'en øverst oppe til at finde det du leder efter, eller brug søgefeltet lige under.
    		</p>
    		
    		<div class="picset">
    			<!-- do NOT space crap with non-breaking spaces, that's CSS' JOB! -->
    			<img src="Grafik/DenLilleHavfrue.png" alt="Ariel">
    			<img src="Grafik/InspectorGadget.png" alt="Isnpector Gadget">
    			<img src="Grafik/LilleJohn.png" alt="Little John">
    		<!-- .picset --></div>
    		<p>
    			For mere info om siden kan du bruge det lille menu ikon oppe til venstre, hvor du også finder links til vores Facebook side som du meget gerne må gå ind og like, samt vores Facebook gruppe hvor du kan snakke med andre om danske stemmer, dubbing, film osv.
    		<p><p>
    			God fornøjelse :)
    		</p>
    	<!-- #content --></div>
    <!-- #top --></div>
    
    <div id="footer">
    	<hr>
    	&copy; DanskeFilmStemmer - Har du rettelser, tilføjelser, spørgsmål eller lign kontakt os gerne på
    	<a href="mailto:mail@danskefilmstemmer.dk">mail@danskefilmstemmer.dk</a>
    	<br>
    	Danskefilmstemmer.dk ejer ikke billedmaterialet, som er (c) de respektive filmstudier.
    	<!-- lose the stupid counter, NOBODY cares, this isn't 1997 -->
    <!-- #footer --></div>
    
    <script src="library.js"></script>
    
    </body></html>
    Code (markup):
    With everything else done from the CSS or scripting... and if your scripting is screwing with the layout or effecting PHP, there's something REALLY foul/incorrect being done.
     
    Last edited: Aug 8, 2017
    deathshadow, Aug 8, 2017 IP
  3. MichHenr

    MichHenr Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #3
    First of all, you really should work on your language... I don't see why you have to be rude...
    Everything has a reason... viewport sizes was invented to make a website look the same on every smart phone no matter the resolution, and it works perfectly... viewport sizes are quite new, so I don't see why you think it's old fashion.. So they invent something no one will use?

    The meta tags for robots are as google describe it should be. The socialmedia links are not in the menu because there is more room right below, with a narrow viewport... The manual breaks instead of <p> is because I want to kontrol where I want the line to break, because I think it looks nicer... Can't see the problem in that... And why do you think nobody cares about the counters..?? I think it is very very important for me to see how many times the different pages has been viewed... Can't see what you mean about that...

    As said the css works perfectly on every platform on the whole site... It is only the javascript part where the viewport doesn't work. So try to understand my question... I have chosen to use the viewport function and it works... How do I get it to work on a page that is loaded via javascript?
    It has nothing to do with the rest of my page since it's working very well...
     
    MichHenr, Aug 8, 2017 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,410
    Likes Received:
    1,504
    Best Answers:
    220
    Trophy Points:
    515
    #4
    I'm a New Englander, it's what we do... and you have SERIOUS deep-rooted issues in your code. Think of me as your own personal Gordan Ramsey or Winston Wolfe.

    ... and is a completely flawed way of even THINKING about site design, which is why your site is broken here on desktop, broken on mobile, and just plain broken. Screens aren't the same size, but pixel density to font-size ratio is a constant. Making the whole layout scale (zoom basically) to the device size might be fine for a DirectX video game, but it's crap usability and a waste of screen space in the mobile world.

    The WCAG says use EM, so use 'em!

    What using that value for font-size has done is result in agonizingly uselessly tiny garbage on my 480x800 mid-range android phone. It's a fist in the face on my tablet. Dicking with font-size based on width is inaccessible broken useless GARBAGE and anyone telling you otherwise isn't qualified to flap their gums on the topic. We have responsive design for a reason, USE IT!

    The viewport sizing isnt' what's old fashioned, the markup it is being applied to is. Tables for nothing, tables for layout, non-semantic markup, it might as well be HTML 3.2 masquerading as HTML 4 tranny! Aka "in transition from 1997 to 1998 coding practices". It has no valid document structure, it has no accessibility aids, the base foundation of semantic markup that should be in place before you even THINK about layout simply isn't there!

    Remember, HTML is about MORE than just sighted users on screen media.

    
    <META NAME="ROBOTS" CONTENT="NOODP">
    <meta name="robot" content="all index follow">
    <meta name="robots" content="all">
    
    Code (markup):
    if you state robots more than once, only the latter one will be applied the earlier is ignored, and there's no such thing as "robot"... and upper-case is HTML 3.2 styling that has TECHNICALLY been invalid (though browsers don't care) since 1997.

    There is NO SUCH THING as "index" or "follow" -- the proper values are noindex and nofollow. You want it indexed and followed, DON'T SAY ANYTHING!

    "all" is the default state, and values are COMMA delmited, not space limited. With no commas that second one IF it were 'robots' and not the non-existent 'robot' would STILL be invalid.

    As such that first one is invalid gibberish, the second one does nothing AND has invalid gibberish content, and the final one serves no legitimate purpose unless you're overriding a screwed up server-side setting.

    Meaning NONE of those should even be in the code! Actually, no. That's not fair.

    <meta name="robots" value="noodp">
    Code (markup):
    Would be the only one that does anything once rewritten to be modern/valid code.

    By which time you're in CSS3 capable browsers, so flex reverse it. You don't screw with the logical document structure in the markup just because "ooh, pretty"

    Non-semantic markup -- a giant middle finger to why HTML even exists, and users on screen readers (software that reads the page aloud), braille readers -- and of course, SEARCH ENGINES. They are PARAGRAPHS grammatically, so you mark them up as paragraphs. You have a problem with them being too wide, that's what max-width is for, and as the width shrinks, so should the number of them per line without plowing the font-sizes down to uselessly tiny!

    How many websites written after 2000 do you see that garbage on? That's right, ZERO. It as a cute "hey look at me" for like two years, then it stopped mattering to VISITORS. If you want those numbers for YOU, that's what your server logs via tools like analog or webalizer are for, or third party tracking like Google Analytics does. Don't waste the visitors bandwidth and time on tracking information they REALLY don't give a flying purple fish about AND that's redundant to something your hosting should already be tracking!

    Methinks we have radically different definitions of the words "working" and "perfectly". Again, 1997 outdated non-semantic HTML with broken layout methodology is a giant middle finger to a LOT of users, AND why HTML even exists in the first bloody place!

    HTML is for saying what things ARE, gramatically. If you are choosing ANY of your HTML tags based on what you want it to look like, (apart from neutral tags like span and DIV, and even then...) you are choosing all the wrong tags for all the wrong reasons! You want to control the appearance, that's CSS' job.

    As I'm always having to explain, based on the professional writing norms on which HTML was based, the H1 is the heading that EVERYTHING on every page of the site (aka a multi-page document) is a part of. H2's are the start of major subsections of the current page. H3 indicate the start of subsections of the h2 preceeding them. H4 indicates the start of a subsection of the H3 preceeding it. Care to guess what H5 and H6 do? HR -- horizontal rule -- indicates a change in topic where heading text is unwanted/unwarranted.

    They do NOT mean "text in different weights or sizes" or "draw a line across the screen"!

    <p>aragraph is for GRAMMATICAL paragraphs. <br>eaks are for pause-level breaks. Tables are for tabular data, not "I want columnar layout". Lists are for short bulletpoints (as in a grammatical bullet point/shorttext, NOT "it has a bullet next to it") or groups of selections. (if they're big enough to warrant a heading, they're no longer list items!)

    NEVER mistake the default appearance of a tag for it's MEANING. Even B, I, and SMALL mean WOULD BE that for grammatical reasons, such as a proper name/legal entity, book title not being <cite>d, or text recieving de-emphasis (respectively). They do NOT mean "must be shown this way" or even "should be shown this way".

    That way ALL users have access, not just the ones magically blessed with being able to use your screen media layout.

    I think your terminology must be banjaxed, as "viewport" has Jack to do with loading a blasted thing via JavaScript... I'm assuming you're referring to AJAXing in content, right? You seem to be shoving the output of the ajax to width and not innerHTML... NOT that you should be using innerHTML directly on the live DOM. NOT that you should be using onkeyup="" since things if something like the Content Security Policy gets implmented, those up and cease to function/exist. (really in the next "HTML" all those onevent attributes should go the way of the dodo) Element.addEventListener (and legacy IE's attachEvent) exists for a reason. USE IT.

    ... and stop making variables for NOTHING.

    So first, clean up this mess:

    
    <input type="text" class="searchbox" id="searchfield" name="searchfield" autocomplete="off" onkeyup="Search(this.value, 'visdiv', 'Vent venligst mens systemet søger');">
    
    Code (markup):
    Into:

    
    <input type="text" id="searchfield" name="searchfield" data-searching="'Vent venligst mens systemet søger'">
    
    Code (markup):
    (don't screw with native autocomplete, that's a GOOD feature)

    (function(w, d) { // self instancing function, isolates scope
    
    	// first some handy helper functions. Lifted from my elementals.js lib
    
    	function newAX(axName) {
    		try { return new activeXObject(axName); } catch (axName) { return false; }
    	} // newAX
    	
    	/*
    		wrapping a 'new' allows us to polyfill the "ajax as parameter" behavior
    		for our readyState handler across all browsers
    	*/
    
    	function xmlHttp(readyHandler) {
    		var x;
    		if (!(x = this.result = w.XMLHttpRequest ? new XMLHttpRequest() : (
    			newAX('Msxml2.XMLHTTP.6.0') ||
    			newAX('Msxml2.XMLHTTP.3.0') ||
    			newAX('Microsoft.XMLHTTP')
    		))) throw new Error('Unable to create XMLHttpRequest or ActiveX XMLHTTP');
    		x.onreadystatechange = function() { readyHandler(x); }
    	}
    	
    	function ajax(readyHandler) {
    		return (new xmlHttp(readyHandler)).result;
    	}
    
    	// cross browser event handler fill
    
    	if (w.addEventListener) {
    		var
    			eventPrevent = function(e) {
    				if (e.stopPropagation) e.stopPropagation();
    				if (e.preventDefault) e.preventDefault();
    			},
    			EventAddCall = function(element, event, callback, captureLevel) {
    				element.addEventListener(event, function(e) {
    					callback(e);
    					if (captureLevel > 1) _.Event.prevent(e);
    				}, captureLevel == 1);
    			};
    	} else {
    		var
    			eventPrevent = function(e) {
    				e.cancelBubble = true;
    				e.returnValue = false;
    			},
    			EventAddCall = function(element, event, callback, captureLevel) {
    				element.attachEvent('on' + event, function(e) {
    					e = w.event;
    					e.target = e.srcElement;
    					e.currentTarget = element;
    					callback(e);
    					if (captureLevel > 0) {
    						e.cancelBubble = true;
    						if (captureLevel > 1) e.returnValue = false;
    					}
    				});
    			};
    	}
    
    	function eventAdd(e, event, callback, prevent) {
    		new EventAddCall(e, event, callback, true == prevent ? 1 : (prevent || 0));
    	};
    
    	/*
    		creating new DOM element and innerHTML on it avoids tripping the parser
    		for the whole live document. This makes our append way faster than doing
    		the same operation directly on the live div#visdiv
    	*/
    	function newSearchOutput(newMarkup) {
    		var newDiv = d.createElement('div');
    		newDiv.id = 'visdiv';
    		newDiv.innerHTML = newMarkup;
    		searchOutput.parentNode.replaceChild(newDiv, searchOutput);
    		searchOutput = newDiv;
    	}
    
    	// then our actual functionality
    	
    	var
    		searchWait = false,
    		// do the gets up-front. Faster in long run
    		searchField = d.getElementById('searchfield'),
    		searchOutput = d.getElementById('visdiv'),
    		searchingText = searchField.getAttribute('data-searching');
    	
    	function searchKeyUp(e) {
    		if (searchWait) clearTimeout(searchWait);
    		else newSearchOutput(searchingText);
    		searchWait = setTimeout(searchStart, 300);
    	}
    	
    	function searchStart() {
    		searchWait = false;
    		var x = ajax(function(x) {
    			if (x.readyState == 4 && x.status == 200)
    				newSearchOutput(x.responseText);
    		});
    		x.open(
    			'GET',
    			'SearchResult.php' + '?searchword=' + encodeURIComponent(searchField.value),
    			true
    		);
    		x.send();
    	}
    	
    	eventAdd(
    		document.getElementById('searchfield'),
    		'keyup',
    		searchKeyUp
    	);
    
    })(window, document);
    Code (markup):
    Might be typo's in there, drive-by coding and all but should give you the general idea. In PRACTICE I probably wouldn't even have the DIV for the output in the markup in the first place, since it's a scripting only element. If it only exists for scripting behavior, it has ZERO business in the HTML. Add it from the scripting with document.createElement and Element.appendChild.

    Of course all of this would be a lot easier if you didn't have the tables for layout / tables for nothing in there.

    I added a 300ms delay before allowing a search to start, so as to not flood with parallel requests. A more robust version would probably also make sure new request are held as pending until a currently executing one has finished.
     
    deathshadow, Aug 9, 2017 IP