fadeToggle with text() bug? - javascript

I'm trying to make a fadeToggle effect on jQuery,
the toggle effect works fine only in the second click on the <h1> tag.
in the first click it showing up and hide right after.
noticed that if I remove the text("how are you") method and put the inside the paragraph tag, it works perfectrly.
wondering why it doesn't work the first way.
This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('h1').click(function(){
$('p').text("how are you").fadeToggle(500);
});
});
</script>
</head>
<body>
<h1>Hello jquery</h1>
<p></p>
</body>
</html>

fadeToggle works the same way as e.g. toggle (applies opposed attribute). And since the default state for the p element at the begininng is display: inline (is visible), then the next default action will be hiding it. That's why you have to define it initially as hidden.
$(document).ready(function() {
$('h1').click(function() {
$('.x').text("how are you").fadeToggle(500);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello jquery</h1>
<p class='x' hidden></p>

It works correctly actually - the paragraph element is shown and by clicking on the heading, the function inserts text in it and then toggles fade. As the element is shown, by default (since there are no rules attached to it that would otherwise hide it), the fadeToggle will transition from shown to hidden state.
As stated in the comment above, to make fadeToggle begin by fading an element in, you should first hide the element (either via CSS or via JS, depending on your needs).

Related

Input field loses focus if I don't hold down left-mouse click

This is 100% of the code:
<html lang="en">
<head>
<title>Test</title>
<script defer src="index.js"></script>
</head>
<body>
<span id="spanName">Hi</span>
</body>
</html>
const mySpan = document.getElementById('spanName');
mySpan.addEventListener('click', e =>{
document.getElementById('spanName').innerHTML = "<form><input type=\"text\" placeholder=\"enter name\"></input></form>"
})
This essentially does what I want it to. When I click on this span, it replaces the inner HTML with the input form. The only problem is that it doesn't stay in focus unless you hold down the left mouse-key. There's nothing else using hover or focus or anything that would compete with the focus.
My best guess is it has something to do with the fact that I'm using the "on-click" event listener, and that's the thing competing with the focus, but clearly the form doesn't just disappear when I unclick the mouse, so the behavior is a little confusing for me.
Heads up, I'm quite new to JavaScript and based off the behavior, I assume that this isn't the correct way to go about this. I had started writing out a bunch of CSS (which I'm also new to), and I currently have a basic navbar at the top full of anchor tags that highlight when I hover over them, but I'm trying to add this into the navbar as a span so that it says "Login" and then when the user clicks on it, the span changes into a login/password form without affecting the other components of the navbar.
That said, aesthetically everything appears to working the way I intended to except for this focus issue. Since it's a problem in this minimal example, I'm assuming it's an issue independent of the other code I've written
Thanks in advance!
Just define an Id to your input and after call the focus function.
const mySpan = document.getElementById('spanName');
mySpan.addEventListener('click', e =>{
document.getElementById('spanName').innerHTML = "<form><input type=\"text\" id=\"myInput\" placeholder=\"enter name\"></input></form>";
document.querySelector("#myInput").focus();
})
<html lang="en">
<head>
<title>Test</title>
<script defer src="index.js"></script>
</head>
<body>
<span id="spanName">Hi</span>
</body>
</html>
Adding .focus() on the input element will help, as #Vinicius has demonstrated in his answer.
I modified your HTML a bit in that I replaced your <span> with a <form> element. In order to make it behave like a span I added some display:inline-block style to it. I also added an .onsubmit handler that will process the input value after you press return.
document.getElementById('frmName').onclick = e =>{
const frm=e.target
frm.innerHTML = "<input type=\"text\" placeholder=\"enter name\">";
const inp=frm.children[0];
frm.onsubmit=ev=>(console.log("you entered:",inp.value),false)
inp.focus();
}
form {display:inline-block; cursor: pointer}
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
abc<form id="frmName">Hi, click me!</form>def
</body>
</html>

I'm having an issue where the 'mouseover' event is simply starting before I even mouseover the selected element

As soon as I load or reload the page. The gif i've included in the html starts playing.
$('.text').mouseover(function() {
$('.hover').css("visibility", "visible"); })
$('.text').mouseout(function() {
$('.hover').css("visibility", "hidden"); });
I want the gif to start whenever I hover over the relevant element and stop when I take my cursor off. This JS is in a script tag within the body of HTML doc. It works after I hover over the 'text' element for the first time. Would love some guidance on what I am doing wrong.
It's likely that the visibility of the image is visible on the initial page load. When you do your first mouseover, then mouseout, it gets set to hidden, which is your expected behavior. Try setting the visibility of the img to hidden, by one of these methods:
Add a style in the head of the page:
<html>
<head>
<style>
img.hover { visibility: hidden; }
</style>
</head>
<body>
<img src='path/to/image.gif' class='hover' />
</body>
</html>
Or, set the style inline in the image itself:
<html>
<body>
<img src='path/to/image.gif' class='hover' style='visibility: hidden' />
</body>
</html>

What does this block of JavaScript code do?

I am very new to JavaScript, jQuery and HTML etc. And I am supposed to implement this block of code (below) in a project and I am not quite sure what it is meant to do:
$(document).ready(function(){
$("body").click(function(){
$(this).hide();
});
});
I'm assuming it simply hides any element that is clicked.
You are correct, it hides everything inside of the HTML element. It is also important to note that it is written using jQuery, which is a JavaScript library that has helper functions to make JavaScript more accessible to use.
Here is one line at a time:
Wait for the page to finishing loading in the browser (aka the DOM, or document object model):
$(document).ready(function(){
});
When the user fires the click event on the body element, run the following function:
$("body").click(function(){
});
Hide the body:
$(this).hide();
this (in this context) refers to the body element targeted in the previous line, this is the same as writing: `$('body').hide();
this refers to something different based on the context in which it is used. In this example it is used in an event, so it refers to the element that received that event (body). See W3Schools.
.hide() is a built in jQuery function that sets the element to display: none;
$(document).ready is called when the page is ready for javascript to be executed. $("body") selects the body, the body of the document is where all of the visible HTML elements are shown. The click event is triggered when well, the element is clicked. $(this) selects the current element being operated on, which is the body. the hide function hides the selected element, which in this case is the body. So this code hides the body of the HTML page resulting in all visual elements being hidden.
It's simple, it puts an "on click" event on the body element.
So that means, when you click the body element. It will hide everything in between the opening <body> and the closing </body> tags
<body>
<!--everything in here will be hidden once body element is clicked-->
</body>
That code will make it so that clicking on any element on the page will cause the body element to hide.
That is - unless the element has it's own onclick functionality assigned that stops the event from bubbling up to the body element's onclick by using the event.stopPropagation() function.
Note: You could also have a call to event.stopPropagation() within the event handler rather than just having it as the event handler.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("body").click(function() {
$(this).hide();
});
});
</script>
<html>
<head>
<title>Testing javascript function</title>
</head>
<body>
<p>Here is one paragraph</p>
<p>Here is a second paragraph</p>
<p>Clicking on any element will hide the entire body element.</p>
<input type="button" value="random button" onclick="event.stopPropagation()" />
</body>
</html>
It is pretty straight forward.
Sample HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
...
</body>
</html>
Js:
$(document).ready(function(){ //executes when document model is ready
$("body").click(function(){ //once u click anywhere on the page this function will be executed
$(this).hide(); //hides everything between <body></body>
});
});

Hyperlinking an iFrame?

I'm not sure if this is even possible.
I've got the following code;
<iframe src="http://www.domain.com/content.html" width="200" height="50"></iframe>
Now, I would have assumed that would've hyper-linked the entire iFrame area, however it only hyperlinks the border.
Is it possible to hyperlink the entire iframe area?
no, that's not valid. you can't even reliably get a click event off of the element containing the iframe.
e.g.,
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#bob').click(function(e){
alert('hi');
});
});
</script>
</head>
<body>
<div id="bob" style="padding:100px;background:red;"><iframe src="http://www.google.com"></iframe></div>
</body>
</html>
notice that if you click the iframe, no alert fires - but if you click anywhere else (in red), it will. if this were otherwise, there'd be abuse...
What actually do you mean by "hyperlink the iframe"?
You could try to use an onclick event for the iframe, or position a div with an onclick and transparent background above the iframe. Another possibility is to set the a to display: block and position it above the iframe.

Is there a HTML opposite to <noscript>?

Is there a tag in HTML that will only display its content if JavaScript is enabled? I know <noscript> works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.
The only way I know how to do this is with the document.write(); method in a script tag, and it seems a bit messy for large amounts of HTML.
Easiest way I can think of:
<html>
<head>
<noscript><style> .jsonly { display: none } </style></noscript>
</head>
<body>
<p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
No document.write, no scripts, pure CSS.
You could have an invisible div that gets shown via JavaScript when the page loads.
I don't really agree with all the answers here about embedding the HTML beforehand and hiding it with CSS until it is again shown with JS. Even w/o JavaScript enabled, that node still exists in the DOM. True, most browsers (even accessibility browsers) will ignore it, but it still exists and there may be odd times when that comes back to bite you.
My preferred method would be to use jQuery to generate the content. If it will be a lot of content, then you can save it as an HTML fragment (just the HTML you will want to show and none of the html, body, head, etc. tags) then use jQuery's ajax functions to load it into the full page.
test.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$.get('_test.html', function(html) {
$('p:first').after(html);
});
});
</script>
</head>
<body>
<p>This is content at the top of the page.</p>
<p>This is content at the bottom of the page.</p>
</body>
</html>
_test.html
<p>This is from an HTML fragment document</p>
result
<p>This is content at the top of the page.</p>
<p>This is from an HTML fragment document</p>
<p>This is content at the bottom of the page.</p>
First of all, always separate content, markup and behaviour!
Now, if you're using the jQuery library (you really should, it makes JavaScript a lot easier), the following code should do:
$(document).ready(function() {
$("body").addClass("js");
});
This will give you an additional class on the body when JS is enabled.
Now, in CSS, you can hide the area when the JS class is not available, and show the area when JS is available.
Alternatively, you can add no-js as the the default class to your body tag, and use this code:
$(document).ready(function() {
$("body").removeClass("no-js");
$("body").addClass("js");
});
Remember that it is still displayed if CSS is disabled.
I have a simple and flexible solution, somewhat similar to Will's (but with the added benefit of being valid html):
Give the body element a class of "jsOff". Remove (or replace) this with JavaScript. Have CSS to hide any elements with a class of "jsOnly" with a parent element with a class of "jsOff".
This means that if JavaScript is enabled, the "jsOff" class will be removed from the body. This will mean that elements with a class of "jsOnly" will not have a parent with a class of "jsOff" and so will not match the CSS selector that hides them, thus they will be shown.
If JavaScript is disabled, the "jsOff" class will not be removed from the body. Elements with "jsOnly" will have a parent with "jsOff" and so will match the CSS selector that hides them, thus they will be hidden.
Here's the code:
<html>
<head>
<!-- put this in a separate stylesheet -->
<style type="text/css">
.jsOff .jsOnly{
display:none;
}
</style>
</head>
<body class="jsOff">
<script type="text/javascript">
document.body.className = document.body.className.replace('jsOff','jsOn');
</script>
<noscript><p>Please enable JavaScript and then refresh the page.</p></noscript>
<p class="jsOnly">I am only shown if JS is enabled</p>
</body>
</html>
It's valid html. It is simple. It's flexible.
Just add the "jsOnly" class to any element that you want to only display when JS is enabled.
Please note that the JavaScript that removes the "jsOff" class should be executed as early as possible inside the body tag. It cannot be executed earlier, as the body tag will not be there yet. It should not be executed later as it will mean that elements with the "jsOnly" class may not be visible right away (as they will match the CSS selector that hides them until the "jsOff" class is removed from the body element).
This could also provide a mechanism for js-only styling (e.g. .jsOn .someClass{}) and no-js-only styling (e.g. .jsOff .someOtherClass{}). You could use it to provide an alternative to <noscript>:
.jsOn .noJsOnly{
display:none;
}
In the decade since this question was asked, the HIDDEN attribute was added to HTML. It allows one to directly hide elements without using CSS. As with CSS-based solutions, the element must be un-hidden by script:
<form hidden id=f>
Javascript is on, form is visible.<br>
<button>Click Me</button>
</form>
<script>
document.getElementById('f').hidden=false;
</script>
<noscript>
Javascript is off, but form is hidden, even when CSS is disabled.
</noscript>
You could also use Javascript to load content from another source file and output that. That may be a bit more black box-is than you're looking for though.
Here's an example for the hidden div way:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*[data-when-js-is-on] {
display: none;
}
</style>
<script>
document.getElementsByTagName("style")[0].textContent = "";
</script>
</head>
<body>
<div data-when-js-is-on>
JS is on.
</div>
</body>
</html>
(You'd probably have to tweak it for poor IE, but you get the idea.)
My solution
.css:
.js {
display: none;
}
.js:
$(document).ready(function() {
$(".js").css('display', 'inline');
$(".no-js").css('display', 'none');
});
.html:
<span class="js">Javascript is enabled</span>
<span class="no-js">Javascript is disabled</span>
Alex's article springs to mind here, however it's only applicable if you're using ASP.NET - it could be emulated in JavaScript however but again you'd have to use document.write();
You could set the visibility of a paragraph|div to 'hidden'.
Then in the 'onload' function, you could set the visibility to 'visible'.
Something like:
<body onload="javascript:document.getElementById(rec).style.visibility=visible">
<p style="visibility: visible" id="rec">This text to be hidden unless javascript available.</p>
There isn't a tag for that. You would need to use javascript to show the text.
Some people already suggested using JS to dynamically set CSS visible. You could also dynamically generate the text with document.getElementById(id).innerHTML = "My Content" or dynamically creating the nodes, but the CSS hack is probably the most straightforward to read.

Categories