Why is the imagine not displayed while beeing "inline". js/html - javascript

I want to show and hide a picture by using one button. when it's clicked, the picture is displayed and a variable is set to 1. so that when you press the button the next time, the picture will be hidden again.
After the button is pressed, I console.log the value of set variable + if the picture is displayed or not. Console says that the Picture is "inline". But the picture is not on my screen.
I think all you need is the js function. If you need more information. just comment. thank's!
<script>
function showHideM(){
let open;
open = 0
if (open == 0){
open = 1;
document.getElementById("melmanId").style.display = "inline";
console.log(open)
console.log(document.getElementById("melmanId").style.display)
return;
}
if (open == 1){
open = 0;
document.getElementById("melmanId").style.display = "none";
}
}
</script>

You don't really need flags to maintain the state of the image's visibility. You can use classList's toggle method to toggle a class on/off or, in this case, visible/hidden, which makes things a little easier.
// Cache the elements, and add an event listener
// to the button
const img = document.querySelector('img');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
// Toggle the "hidden" class
function handleClick() {
img.classList.toggle('hidden');
}
.hidden { visibility: hidden; }
img { display: block; margin-bottom: 1em; }
button:hover { cursor: pointer; background-color: #fffff0; }
<img class="hidden" src="https://dummyimage.com/100x100/000/fff">
<button>Click</button>
Additional documentation
addEventListener
querySelector

Note: this will replace all the styles applied to 'melmanId'
<script>
let show = true;
function showHideM() {
show = !show;
if(show){
document.getElementById("melmanId").style.display = "inline";
}else{
document.getElementById("melmanId").style.display = "none";
}
}
</script>

Related

Add a style to html and body via onclick

I am having a problem with my hamburger menu, my background page scrolling when it is open. I noticed that if I add 'overflow: hidden' to the body and html, it fixes the problem. However, when I close the menu, the body is obviously still locked. How can I add javascript to cancel these styles from the body and html?
This is what I have tried:
<div class="navbar_toggle" onclick="nonscroll(this)">
<script>
function nonscroll(elem) {
document.body.style.overflow = "hidden";
document.html.style.overflow = "hidden";
}
</script>
When I click the button, I want these styles to apply. When I close the menu, I want them to disappear. Is there a very simple way to fix this?
Solution
Copy from this example, paste into your page:
function FixScrollToggle (node) {
var target = document.body;
function isClicked () {
return target.classList.contains('fixScrollToggle--on');
}
function freeze() {
target.classList.add('fixScrollToggle--on');
}
function unFreeze() {
target.classList.remove('fixScrollToggle--on');
}
function onClick (e) {
if (isClicked()) { return unFreeze(); }
return freeze();
}
node.addEventListener('click', onClick, false);
}
document.addEventListener('DOMContentLoaded', function () {
Array.prototype.slice.
call(document.querySelectorAll('[data-apply-fix]')).
forEach(FixScrollToggle);
});
.fixScrollToggle--on {
overflow: hidden;
background-color: #c00;
}
<div class="navbar_toggle" data-apply-fix>Click me</div>
It's not the most easy way, but it's a clean and relatively easy way. Just put the JS code into a <script> tag in your page.
Explanation
This code works by adding a click eventlistener to each HTML element which has a data-apply-fix attribute set. This way, you can attach the same behaviour to multiple elements on your page.
The behaviour of manipulating the CSS is entirely done with the CSS class fixScrollToggle--on. This way, you have a very clean separation of concerns.
In nonscroll() function, you need to do two things:
Check if nav is hidden or shown.
When you know the nav visibility, you can update style for body and html.
<div class="navbar_toggle" onclick="nonscroll(this)">
<script>
function nonscroll(elem) {
// check if navbar is hidden or shown
// if nav is hidden: "body overflow is 'hidden'"
// else "body overflow is 'static'"
var nav = document.getElementsByClassName("navbar_toggle");
var nav_hidden = (window.getComputedStyle(nav[0]).visibility === "hidden")
if(nav_hidden) {
document.body.style.overflow = "hidden";
document.html.style.overflow = "hidden";
} else {
document.body.style.overflow = "static";
document.html.style.overflow = "static";
}
}
</script>
Simple ways to do that is using toggle class on click listener, as your code above it could:
var toggle = document.getElementsByClassName('navbar_toggle')[0];
var html = document.getElementsByTagName('html')[0];
var body = document.getElementsByTagName('body')[0];
var all = [html,body];
toggle.addEventListener( 'click', function() {
for ( var i=0; i < all.length; i++ ) {
all[i]classList.toggle('is-active');
}
});
Then ur css should be:
html, body {
overflow: auto;
}
.is-active {
overflow: hidden;
position: fixed; // prevent body scrolling for safari and ios
}

How to know when a particular button is clicked in Javascript?

I'm making a function that displays a modal, and the modal has two buttons. I want this function to wait until one of the two buttons has been clicked, and return a value that corresponds to which button is clicked.
Here's a sample code that I came up with:
function myFunc()
{
var val=0;
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
val = 1;
}
buttonB.onclick = function(){
//do something
val = 2;
}
while(val == 0);
return val;
}
The problem in this code is that the page becomes unresponsive because of the infinite loop, hence it isn't possible to change the value of val once initialised.
To be more precise, I want the main thread (on which myFunc is being implemented) to sleep until one of the other two threads (each of buttonA and buttonB) is clicked.
Is there some other work-around for this ? Please answer in Javascript only (no jQuery). Thanks.
Try something more like this:
function myFunc()
{
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
differentFunc(1)
}
buttonB.onclick = function(){
//do something
differentFunc(2)
}
}
This is a different way to make the function more versatile (edited per your comment):
function myFunc(callback)
{
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
callback(1)
}
buttonB.onclick = function(){
//do something
callback(2)
}
}
and call it like
myFunc(function(result) {
// do stuff with result
}
Javascript is naturally single-threaded. Any code that waits infinitely like that will cause a hangup and disallow input. There are ways to write async functions, namely using Promises like I did for a minute there, but it's generally easier to make your code work synchronously.
If I understand the OP's purpose is to create a modal with 2 choices like a confirm()? But for some reason confirm() isn't suitable? So a value on each button and it waits for user interaction? Unless I'm missing something fairly important, I have made a dynamically generated modal (no manual markup) that has 2 buttons. The purpose and result elude me so I left it with one event listener and a function with a simple ternary condition to which the alerts can be replaced by appropriate statements or expression at OP's discretion.
SNIPPET
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
.modal {
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
background:transparent;
}
.ui {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: table-cell;
border: 3px ridge grey;
border-radius: 6px;
}
button {
font-size: 24px;
}
</style>
</head>
<body>
<script>
var frag = document.createDocumentFragment();
var modal = document.createElement('div');
var ui = document.createElement('div');
var on = document.createElement('button');
var off = document.createElement('button');
modal.className = 'modal';
ui.className = 'ui';
on.id = 'on';
on.textContent = 'On';
off.id = 'off';
off.textContent = 'Off';
frag.appendChild(modal);
modal.appendChild(ui);
ui.appendChild(on);
ui.appendChild(off);
ui.addEventListener('click', status, false);
function status(e) {
var tgt = e.target.id;
tgt === 'on' ? alert('ON!') : alert('OFF!');
}
document.body.appendChild(frag);
</script>
</body>
</html>

display: none/block onclick messes up

I am having troubles for some reason, and I can't seem to find out how...
I am making a quiz, which starts with a start button, and has buttons "next" and "prev" buttons.. When I hit the start button, the question 1 and answer 1 will come up and the start button disappears, when I then hit next it is loading in the second question, but not the answer 2
my code:
// Hide / Show actions
function hideStartButton() { document.getElementById("start-button").style.display = "none";}
function showAnswers1() { document.getElementById("answers1").style.display = "block"; }
function hideAnswers1() { document.getElementById("answers1").style.display = "none"; }
function showAnswers2() { document.getElementById("answers2").style.display = "block"; }
function hideAnswers2() { document.getElementById("answers2").style.display = "none"; }
Complete code: http://jsfiddle.net/5jz092cb/
it does load answers2 when I don't use hideAnswer1(); else it comes up blank?
CSS
.hidden {display: none;}
JavaScript
change('answers1','hidden');
change(document.getElementById('answers1'),'hidden');
//etc.
function change(id,c)
{
if (id_(id)) {id_(id).className = c; if (id_(id).className=='') {id_(id).removeAttribute('class');}}
else if (id) {id.className = c; if (id.className=='') {id.removeAttribute('class');}}
else {alert('Error: the class id \''+id+'\' was not found or has not yet been imported to the DOM.\n\nNew class intended: '+c);}
}
Also you need to hide and show layers simultaneously often in these kind of scenarios so you may very well need to do something like loop through and hide all the elements except the one you want to hide.

Prevent link dragging, but still allow text highlighting

I have some data in a table where clicking it will navigate you elsewhere, but people are requesting the ability to highlight the text to be able to copy/paste it elsewhere. Since they are links, the default behavior in HTML is to drag the link... I don't know why or how that is useful, but I want to disable that on certain links.
TL;DR: I want to be able to highlight the text of a link and not drag it.
The gif below should help explain my issue.
The following methods are NOT what I want:
I have seen examples that prevent both highlighting & dragging using something like this
<a draggable="false" href="#">
or this
.no-drag {
user-drag: none;
}
Or this
myElement.ondragstart = function () {
return false;
};
But obviously that is not what I need here.Is what I want possible to do?
In Google Chrome this works
user-select: none;
-webkit-user-drag: none;
#Julien Grégoire's answer above put me on the right track for this, but the below code is the basics of what I ended up using.
var clickedEl = document.getElementById("test");
var limit = 5;
var mouseMoved = false;
function resetEvents() {
clickedEl.onmousemove = null;
clickedEl.ondragstart = null;
clickedEl.onmouseleave = null;
mouseMoved = false;
}
clickedEl.onmousedown = function (downEvent) {
if (clickedEl.attributes.href) {
clickedEl.onclick = function (clickEvent) {
if (mouseMoved) {
clickEvent.preventDefault();
}
resetEvents();
};
}
clickedEl.onmouseleave = function () {
resetEvents();
};
clickedEl.onmousemove = function (moveEvent) {
// This prevents the text selection being dragged
clickedEl.ondragstart = function (dragEvent) {
dragEvent.preventDefault();
};
if (Math.abs(moveEvent.x - downEvent.x) >= limit || Math.abs(moveEvent.y - downEvent.y) >= limit) {
// If user clicks then moves the mouse within a certain limit, select the text inside
window.getSelection().selectAllChildren(clickedEl);
mouseMoved = true;
}
};
};
<a id="test" href="http://stackoverflow.com">Click or select</a>
I'm super late to answer but I'm just gonna leave it here:
Just put draggable="false" inside <a> tag,
<a draggable="false" href="./"></a>
then in CSS you put:
body {
-webkit-user-drag: none;
}
You could detect if user moves the mouse after the click and if so manage selection using window.getSelection. Something like this for example:
var linkEl = document.getElementById('test')
linkEl.onmousedown = function(downEvent) {
var clickedEl = downEvent.target;
var mouseMoved = false;
clickedEl.onmousemove = function() {
// If user clicks then moves, select the whole link
window.getSelection().selectAllChildren(clickedEl);
// Set a flag to prevent opening the link
mouseMoved = true;
// Reset mousemove, else it'll run constantly
clickedEl.onmousemove = null;
// This is only to prevent having the text selection being dragged
clickedEl.ondragstart = function(dragEvent) {
dragEvent.preventDefault();
}
}
if (mouseMoved) {
// If mouse has moved, prevent default
downEvent.preventDefault();
}
}
<a draggable="false" id="test" href="http://stackoverflow.com">Click or select</a>
This is the simplest solution that worked for me. You can change '*' to 'a'.
*, *::after, *::before {
-webkit-user-select: none;
-webkit-user-drag: none;
-webkit-app-region: no-drag;
}

Hidden div flashing on page load

In my Rails app, I'm trying to hide a div (box) on page load in the Javascript function below. This function loops through a series of checkboxes with the same name (cb). If any of the checkboxes are checked, it should show the div.
function BoxCheck(cb,box){
var cbs=document.getElementsByName(cb);
var d=document.getElementById(box);
d.style.display = 'none';
var flag_check=0
for (var zxc0=0;zxc0<cbs.length;zxc0++){
if (cbs[zxc0].checked){
flag_check=flag_check+1
} else
{ }
}
if (flag_check > 0){
d.style.display = 'block';
document.getElementById('multi_control_spacer').style.display = 'block';
} else {
d.style.display = 'none';
document.getElementById('multi_control_spacer').style.display = 'none';
}
}
The function fires on load with:
<body onload="javascript:BoxCheck('doc_ids[]','multi_control');">
The problem is that when no checkboxes are selected, the div flashes on momentarily, and then disappears.
Here's the CSS:
#multi_control {
padding: 10px;
background: #333;
}
I tried setting the css to display:none, but then I can't seem to make it switch to back to display:block with Javascript.
Why not? Have you tried:
element.style.display = 'block';
How about putting style="display:none" into the div tag so it's hidden to begin with?

Categories