Setting and removing the onclick attribute - javascript

So I am trying to remove the onclick attribute from the div "#link". It will not remove. It also will not work with setting an attribute for onclick. Anything that seems to edit onclick doesn't seem to effect it. I need it to remove the attribute of "of onclick" and set it to another one. Thanks
$(document).ready(function() {
var attribute = $('#link').attr("onclick");
var linklength = (attribute.split("'").length - 1);
if (linklength > 5) {
$('#link').removeAttr("onclick");
$('#link')[0].setAttribute('onclick', 'test');
console.log(attribute);
console.log(linklength);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="link" onclick="skinPopup('UserDirectory','for name ','#userBio');">
</div>
<p id="title">Te'st</p>

Not sure what you are trying to achieve, as you already using jQuery you could simplify things. Something like this
$(document).ready(function() {
var $link = $("#link");
function skinPopup(directory, statement, id){
console.log(directory, statement, id);
}
$link.on('click', function(){
skinPopup('UserDirectory','for name ','#userBio');
});
//removing click event after 3s
setTimeout(function(){
$link.addClass('red');
$link.off('click');
// attaching mouseover and mouseout event
$link.on('mouseover', function(){
$(this).removeClass('red');
}).on('mouseout', function(){
$(this).addClass('red');
})
}, 3000)
});
.red{
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="link">
Link
</div>
<p id="title">Te'st</p>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Note, instead of removing click event on condition I removed it after a particular time, you could add condition based on your requirements. Both attribute and linklength seemed unnecessary, that's why I removed it.
To learn more about event listeners
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
http://api.jquery.com/on/
http://api.jquery.com/off/
Hope this helps, let me know if you have any questions.

Related

Making an Element draggable without ID

I'm trying to make divs created with .createElement be draggable. It works fine with divs that are already created like below:
<div>
This can be dragged around, but outputs cannot?!
</div>
but when I create new divs with the function addElement(), it doesn't work.
In more detail here is what my code aims to do:
user inputs text -> clicks input button and the user input(s) are outputted on the screen and can be dragged.
Full code:
function addElement () {
var text = document.getElementById("input").value;
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
document.getElementById("input").value = " ";
}
$( function() {
var div = document.getElementsByTagName('div');
$( div ).draggable();
} );
div { width: 150px; height: 150px; padding: 0.5em; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input"type="text" placeholder=" text">
<button onclick="addElement()" >Input</button>
<p>Outputs:</p>
<script src="script.js"></script>
</body>
</html>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>
When you load the page, the draggable gets attached to the div element which is already loaded. But when you dynamically create a new element, the draggable is not re-attached to the new div. So, whenever you add a new div, you need to re-attach the draggable event to it:
function addElement() {
var text = document.getElementById("input").value;
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
$(function() {
var div = document.getElementsByTagName('div');
$(div).draggable();
});
document.getElementById("input").value = " ";
}
$(function() {
var div = document.getElementsByTagName('div');
$(div).draggable();
});
div {
width: 150px;
height: 150px;
padding: 0.5em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input" type="text" placeholder=" text">
<button onclick="addElement()">Input</button>
<p>Outputs:</p>
<script src="script.js"></script>
</body>
</html>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>
When you load the page, the draggable gets attached to the div element which is already loaded. But when you dynamically create a new element, the draggable is not attached to the new div. Whenever you add a new div, you need to re-attach draggable event to it.
You only run
$( function() {
var div = document.getElementsByTagName('div');
$( div ).draggable();
} );
when your app loads for the first time, therefore newly created divs are not draggable.
When you want the new divs to be draggable, you have to add $( newDiv ).draggable() to your addElement() function.
You are using $(callback), which only calls the function once when the DOM is loaded.
However, when you add new elements, they will not be made draggable since the function that does it has already run.
To make the new elements draggable too, you will need to call jQuery.draggable() on them as well after creating them.
This means, you should add newDiv.draggable() inside your function that creates the elements.
Sidenote
When using an API like jQuery, you should try to stick to it rather than the native methods to make understanding it easier, since one wouldn't have to go back and forth in their mindsets.
Subnotes
You have incorrect HTML since you have a <div> after closing both <body> and <html>, and are trying to close them again at the end. Since HTML disallows elements outside of <body>, most browsers automatically correct this mistake. However, you should format the HTML correctly yourself.
Creating jQuery-elements using $(document.createElement('div')) instead of using $('<div>') is (minimally) faster, hence I use it below
Do not add the onclick-listener in the HTML, instead, add it using JavaScript. Adding the listener inline would require the function to be exposed in the global scope, and would pollute the global namespace. Listeners do not require to be named, and can easily be added in JS, allowing to not expose the functions to the global scope.
Making your code use mostly jQuery would make it look like this:
$(function() { // Executed once DOM loaded
// Make all pre-existing 'div's draggable
$('div').draggable();
// Add the 'onclick'-listener using jQuery
$('button').click(function() {
// Creating jQuery-element this way; read about the reason in the sub-notes
var newDiv = $(document.createElement("div"));
newDiv.text($('#input').val()); // Set the text to the value of 'input'
newDiv.draggable(); // Make it draggable
$('body').append(newDiv); // Append it to the body
$('#input').val(''); // Set 'input's value to ""
});
});
div {
width: 150px;
height: 150px;
padding: 0.5em;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input id="input" type="text" placeholder="text">
<button>Input</button>
<p>Outputs:</p>
<div>
This can be dragged around, but outputs cannot?!
</div>
</body>
</html>

Why the JavaScript function doesn't work?

If you click the button, it should have showed, but it doesn't.
Is any wrong here?
I have written many JavaScript files in this way, and tried many ways like changing the position of JavaScript code anywhere. But all the files I wrote don't work
Thanks in advance!
An instance :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class = "show" onclick = "JavaScript : show();">Show</button>
<script type = "text/JavaScript">
function show() {
document.querySelector("debug").style.display = "flex";
}
</script>
</body>
</html>
Thanks to all of you!
About .querySelector()
The Document method querySelector() returns the first Element within the document that matches the specified selector. [...] The selector is a CSS selector string.
- MDN web docs
You should, therefore, put in your code:
document.querySelector(".debug")
You can also select HTML elements by their tags, for example, you want to select the first div:
document.querySelector("div")
document.querySelector("div").style.color = "lightgreen"
<div>Hello World</div>
Imagine you had your own HTML tag: <hello>, then you can select all hello elements with:
document.querySelector("hello")
document.querySelector("hello").style.color = "lightblue"
<hello>Hello World</hello>
Side note on inline eventListeners
Also in HTML for inline event listener instead of:
<button class = "show" onclick = "JavaScript : show();">Show</button>
you can simply write:
<button class = "show" onclick = "show();">Show</button>
It is recommended to use JavaScript to initiate these eventListeners instead of having them inline inside your HTML markup. Use the .addEventListener() method:
document.querySelector(".show").addEventListener('click', show)
↑ ↑
event function
type
Back to your code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debug</title>
</head>
<style>
.debug {
display : none;
}
</style>
<body>
<div class = "debug">
<p>Welcome!</p>
</div>
<button class ="show">Show</button>
<script type = "text/JavaScript">
document.querySelector(".show").addEventListener("click", show)
function show() {
document.querySelector(".debug").style.display = "flex";
}
</script>
</body>
</html>
Last thing
Also it's better to keep HTML, JavaScript and CSS all in separate files, for instance:
- index.html
- style.css
- script.js
And call the CSS and JavaScript files in your HTML file with the link (preferably inside <head>) and script (at the bottom of <body>) tags:
<link rel="stylesheet" type="text/css" href="style.css">
And
<script src="script.js"></script>
For class selector you need to add a dot (.) e.g. .debug
Also, in HTML, you can simply have onclick as onclick="show();"
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="show();">Show</button>
You were not passing class to querySelector. Set ".debug" instead of "debug".
Below is working code:
function show() {
document.querySelector(".debug").style.display = "flex";
}
.debug {
display: none;
}
<div class="debug">
<p>Welcome!</p>
</div>
<button class="show" onclick="JavaScript : show();">Show</button>
queryselectors requires . and # for class and ID selector:
querySelector(".debug")

Button onClick FadeIn Text

I'd like that somebody could give me an heads-up with the code to achieve this events:
User clicks a button;
Button disappears;
Text fades in saying "Saved!" in the SAME POSITION of the button;
Text fades out;
Button (from 2nd step) reappears.
Here's the code of the button:
<input type="submit" name="gravarpalp" value="Save" />
Thanks in advance!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$('#saveme').click(function() {
$('#saveme').fadeOut('slow', function() {
$('#saved').fadeIn('slow', function() {
$('#saved').fadeOut('slow', function() {
$('#saveme').fadeIn('slow', function() {
});
});
});
});
});
});
</script>
</head>
<body>
<div id="saved" style="position:absolute;top:10px;left:10px;display:none">Saved</div>
<input type="submit" name="gravarpalp" value="Save" id="saveme" style="position:absolute;top:10px;left:10px;"/>
</body>
</html>
I would use jquery to accomplish this.
First, put the controls inside of a div with the following css properties set
<div>
<span id="fadeSpan" style='position: relative; display: none;>Saved!</span>
<input id="fadeButton" type="submit" name="gravarpalp" value="Save" style='position: relative;' onclick='fadeEffect();' />
</div>
Then add the following function in a script tag. This isn't tested though, it's just to get you started.
function() fadeEffect(){
$('#fadeButton').fadeToggle();
$('#fadeSpan').fadeToggle();
setTimeout(function(){
$('#fadeButton').fadeToggle();
$('#fadeSpan').fadeToggle();
}, 3000);
}
Check out this link. Looks like you should just be able to set the ForeColor of a Label to a color value that has a different alpha value.
button1.Visible = false;
//make label fade in (alpha value++)
//once opacity reaches 255, make it fade out (alpha value--)
button1.Visible = true;
I think you will need some sort of timer so the fade in and out isn't so instant. I'll try explaining better if you need.
EDIT: Sorry, I assumed this was a WinForms app... This won't work for a web application. Try using jQuery or javascript.

Adding an onclick event to a div element

I saw a few similar topics which did help but I have specific problem and didn't manage to solve it alone so if anyone can help out I would appreciate it
I want to add onclick event to a div element.
HTML:
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')"></div>
JavaScript:
function klikaj(i)
{
document.getElementById(i).style.visibility='visible';
}
Wanted result: div with id="rad1" (which is hidden) turns visible, when clicked on div with id="thumb0".
This works when I add it to a button element but don't know how it goes with div elements.
I'm not sure what the problem is; running the below works as expected:
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">knock knock</div>
​<div id="rad1" style="visibility: hidden">hello world</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
<script>
function klikaj(i) {
document.getElementById(i).style.visibility='visible';
}
</script>
See also: http://jsfiddle.net/5tD4P/
maybe your script tab has some problem.
if you set type, must type="application/javascript".
<!DOCTYPE html>
<html>
<head>
<title>
Hello
</title>
</head>
<body>
<div onclick="showMsg('Hello')">
Click me show message
</div>
<script type="application/javascript">
function showMsg(item) {
alert(item);
}
</script>
</body>
</html>
Depends in how you are hiding your div, diplay=none is different of visibility=hidden and the opacity=0
Visibility then use ...style.visibility='visible'
Display then use ...style.display='block' (or others depends how
you setup ur css, inline, inline-block, flex...)
Opacity then use ...style.opacity='1';
Its possible, we can specify onclick event in
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
<script>
function fun1(i) {
document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>
I think You are using //--style="display:none"--// for hiding the div.
Use this code:
<script>
function klikaj(i) {
document.getElementById(i).style.display = 'block';
}
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">Click Me..!</div>
<div id="rad1" class="thumbs" style="display:none">Helloooooo</div>

pass CSS .class as a parameter to javascript function

the goal here is onclick of 1.gif, everything with .panel1 class disappears(style.display.none), and everything with a .panel2 class becomes visable (style.display.inline)
I'm new at this..so I think its just a syntax issue with ' ' or maybe " "
<!DOCTYPE html>
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
document.getElementByClass(panelIn).style.display="inline";
document.getElementByClass(panelOut).style.display="none";
}
</script>
</head>
<body>
<img class="panel1" src=1.gif onclick="panelTransition(panel1,panel2)" />
<img class="panel2" src=2.gif />
</body>
</html>
There is no getElementByClass. It's getElementsByClassName, and it returns an array of items, so you'll need to modify your code to loop through them.
function panelTransition(panelOut, panelIn) {
var inPanels = document.getElementsByClassName(panelIn);
for (var i = 0; i < inPanels.length; i++) {
inPanels[i].style.display = 'inline';
}
var outPanels = document.getElementsByClassName(panelOut);
for (var i = 0; i < outPanels.length; i++) {
outPanels[i].style.display = 'none';
}
}
If you were using a JavaScript library, like jQuery, this would be much easier to do. Also, as has been mentioned, you need quotes around your arguments to panelTransition.
<img class="panel1" src=1.gif onclick="panelTransition('panel1', 'panel2')" />
<img class="panel2" src=2.gif />
<img class="panel1" src=1.gif onclick="panelTransition('panel1','panel2')" />
I think you need quotes there
<html>
<head>
<title>main</title>
<meta charset="utf-8">
<style type="text/css">
.panel1 {display:inline;}
.panel2 {display:none;}
</style>
<script type="text/javascript">
function panelTransition(panelOut,panelIn)
{
// panelIn gets turned on
setDisplay(panelIn,"inline");
// panelOut gets turned off
setDisplay(panelOut,"none");
}
function setDisplay(className,displayState)
{
// retrieve a list of all the matching elements
var list = document.getElementsByClassName(className);
// step through the list
for(i=0; i<list.length; i++) {
// for each element, set the display property
list[i].style.display = displayState;
}
}
</script>
</head>
<body>
<img class="panel1" src="1.gif" onclick="panelTransition('panel1','panel2')" />
<img class="panel2" src="2.gif" onclick="panelTransition('panel2','panel1')" />
</body>
</html>
Or you can accomplish the same in jQuery
// fires when the page is up and running
$(document).ready(function(){
// find all the panel1 elements,
// attach an on click handler
$(".panel1").bind("click", function(){
// find all the panel1 elements
// set their css display property to inline
$(".panel1").css("display","inline");
// find all the panel2 elements
// set their css display property to none
$(".panel2").css("display","none");
});
$(".panel2").bind("click", function(){
$(".panel2").css("display","inline");
$(".panel1").css("display","none");
});
});
You can learn all about jQuery here : http://www.jquery.com/
You'll only be able to get your code to run once, as soon as you click a panel1 image all of the panel2 images will disappear, you won't be able to click them back on ever again.

Categories

Resources