here I have this code.
$(document).ready(function(){
//Variables
var inventory = {storage:'pocket',stuff:0,space:5};
var equip = {
head:'',
chest:'torn shirt',
arms:'',
wrists:'watch',
hands:'',
legs:'torn jeans',
ankles:'',
feet:''
};
var equipNames = [
'torn shirt',
'torn jeans',
'watch',
'boots'
];
var equipPlaces = {
torn_shirt:'chest',
watch:'wrists',
torn_jeans:'legs',
boots:'feet'
}
//Setup
addToInventory('boots',1);
//Intervals
setInterval(function(){
//Text
$('#inventoryTitle').text(inventory.storage+'-'+inventory.stuff+'/'+inventory.space);
$('#equipHead').text(equip.head);
$('#equipChest').text(equip.chest);
$('#equipArms').text(equip.arms);
$('#equipWrists').text(equip.wrists);
$('#equipHands').text(equip.hands);
$('#equipLegs').text(equip.legs);
$('#equipAnkles').text(equip.ankles);
$('#equipFeet').text(equip.feet);
},1);
//Functions
function addToInventory(name,amount){
for(var i=0;i<amount;i++){
if(inventory.stuff>=inventory.space) return;
$('<tr>').text(name).appendTo($('#inventory')).addClass('item');
inventory.stuff++;
}
}
function takeOff(name){
if(equip.head==name) equip.head='';
if(equip.chest==name) equip.chest='';
if(equip.arms==name) equip.arms='';
if(equip.wrists==name) equip.wrists='';
if(equip.hands==name) equip.hands='';
if(equip.legs==name) equip.legs='';
if(equip.ankles==name) equip.ankles='';
if(equip.feet==name) equip.feet='';
}
function isEquip(name){
for(var i=0;i<equipNames.length;i++){
if(name==equipNames[i]) return true;
}
return false;
}
function equip(name){
var name2 = name
name.replace(/ /g,'_');
alert(name);
equip[equipPlaces[name2]]=name;
}
function removeFromInventory(name){
}
//Triggers
$('.equip').click(function(){
var e = $(this).text();
if(e!=''){
if(inventory.stuff<inventory.space){
takeOff(e);
addToInventory(e,1);
}
}
});
$('.item').on('click', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}
});
});
html, body, button {
background-color:black;
color:lime;
font-family:monospace;
text-transform:uppercase;
}
header {text-align:center;}
fieldset {border:1px solid lime;}
td, button {border:1px solid lime;text-align:center;}
html {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>survivor</header>
<fieldset style='float:right;'>
<legend id='inventoryTitle'>storage - stuff / space</legend>
<table id='inventory'></table>
</fieldset>
<fieldset style='float:right;'>
<legend>Equipment</legend>
<table>
<tr><td>Head</td><td id='equipHead' class='equip'></td></tr>
<tr><td>chest</td><td id='equipChest' class='equip'></td></tr>
<tr><td>arms</td><td id='equipArms' class='equip'></td></tr>
<tr><td>wrists</td><td id='equipWrists' class='equip'></td></tr>
<tr><td>hands</td><td id='equipHands' class='equip'></td></tr>
<tr><td>legs</td><td id='equipLegs' class='equip'</td></tr>
<tr><td>ankles</td><td id='equipAnkles' class='equip'></td></tr>
<tr><td>feet</td><td id='equipFeet' class='equip'></td></tr>
</table>
</fieldset>
This is a game I am working on, the current aspect of the game I am working on is the equipment system. It works mostly fine, you can take items off of yourself by clicking them in the equipment fieldset, and they go into your inventory, unless it's full. The problem is trying to put them back on, you should be able to do this by clicking the equipment in your inventory or 'pocket', I have done some testing and I believe the problem is at
$('.item').on('click', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}});
I believe the problem is that JQuery is not recognizing that the items in the inventory have the 'item' class, though if you note in the addToInventory() function I specifically give it the 'item' class, this confuses me. Any help?
Your class="item" elements do not exist at the time you ran the jQuery selector and bound the event handler.
Use a delegated event handler attached to a non-changing ancestor element:
$(document).on('click', '.item', function(){
var i = $(this).text();
alert(i);
if(isEquip(i)){
alert(i);
equip(i);
}
});
document is the default if nothing else is closer.
It works by listening for the event (in this case click) bubbbling up to an ancestor of the element clicked, then applying a jQuery selector at event time. Then applying the function to any matching elements that caused the event. This allows for elements to match even if they were added after the event was registered.
Note: Never use 'body' for delegated mouse events as styling can result in a 0 height, which stops the events bubbling. Use document if nothing else is conveniently closer.
Related
I'm currently in the process of trying to develop a smarter UI for one of my clients. However the only code I can use to develop this 'feature', is pure JS. I have no access to the source HTML or CSS files the only access I have is the ability to inject JavaScript through an external .js file.
I'm not too familiar with JS, but I can work my way around a basic script or two.
Scenario
What we're doing is allowing users to edit PDF Templates online using a software called Core Create. The UI accessed through the browser is quite cluttered and I would like to provide an option to hide and show UI elements <textareas>/<inputs> through the use of checkboxes.
Here is a very basic JS Fiddle that I have built with the
intention of hiding and displaying UI.
The page in question
Above is a screen grab of the page I am working with, on the left you can see the UI and its composition on the right within the 'Inspect Element' tool.
I have come to the conclusion that I need to iterate through the highlighted selection and link them accordingly with seven checkboxes. The result would then be a selection of checkboxes that would hide / display the correct UI element.
The Caveat
In realizing I cannot edit or introduce new HTML I noticed the lack of on-click attributes. So I'm a bit lost on how to invoke the JavaScript I will eventually build.
My Question
With my limited knowledge of JS I don't know how I would iterate though div elements editoraccvar - editoraccvar6 picking out the ones I need to manipulate.
Due to the lack of ID's / Names (I assume it would have to be done using Parent/Child rules somehow, as the classes are widley used by the rest of the UI. I would appreciate a small example demonstrating how I could achieve this, so I can learn from it.
I should clarify, I have already added the checkboxes to the page, I just need to build the JS link between the Checkbox and the UI element I'm attempting to target. You can find all attributes linking to these checkboxes included in the JS Fiddle.
EDIT // A Working Simplified Example;
Due to some confusion I have 'frankensteined' some code together to show the final result I am after. A working example of sorts. The actual result needs to target 7 Checkboxes and 7 Divisions. I'll list thier common properties below.
// This script is already in place and constructed by the system.
// Written inside script tags and located straight after 'editopt1'.
// $(document).ready(function() {
// $('#checkboxopt1').click(function() {
// if ($('#checkboxopt1').val() == 'true') {
// $('#opt1').val('false');
// $('#checkboxopt1').val('false');
// $('#checkboxopt1').prop('checked', false);
// $('#previewrefresh').trigger('click');
// } else {
// $('#opt1').val('true');
// $('#checkboxopt1').val('true');
// $('#checkboxopt1').prop('checked', true);
// $('#previewrefresh').trigger('click');
// };
// });
// });
function exFunction() {
// Check the function is called
console.log("200 : OK");
// grab all elements with the class, .field-summernote
var uiblocks = document.querySelectorAll('.field-summernote');
for (var i = 0; i < uiblocks.length; i++) {
var current = uiblocks[i];
if (current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
// check elements in the array
console.log(current);
// control the elemets in the array.
if (document.getElementById('checkboxopt1').checked) {
uiblocks[0].style.display = 'block'; // display the element
} else {
uiblocks[0].style.display = 'none'; // hide the element
}
}
};
// Trigger the collection the check, and the control.
var x = document.getElementById("checkboxopt1");
x.addEventListener("click", function() {
console.log("Opt");
exFunction();
});
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
Divisions <div class=""></div>
* editoraccvar,
editoraccvar1,
editoraccvar2,
editoraccvar3,
editoraccvar4,
editoraccvar5,
editoraccvar6*
Checkboxes <input id=""></input>
* checkboxopt,
checkboxopt1,
checkboxopt2,
checkboxopt3,
checkboxopt4,
checkboxopt5,
checkboxopt6,*
As far as I can see, your problem boils down to link checkboxes (that seem to have been generated in some way) to "division" parts of your html that you want to hide. Plus, you have to inject javascript code in the page (so I guess the less code the better).
One approach could be as follows:
// Wrap the code in an anonymus function, to avoid clustering the global space.
(function (domElements) {
// This is the callback that will fire when a checkbox is clicked.
function clickCallback() {
// the context of this callback is the DOM element thus we can access its attributes through this.
// extract the checkNumber of the class of the element. This number is the link to the division that we want to hide/show.
var checkNumber = ((/ editoropt(\d*) /).exec(this.className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0];
// Hide/show division, update checkBox state.
toggleElements(division, checkBox, window.getComputedStyle(division).display === 'none');
}
function toggleElements(division, checkBox, isShown) {
// Toggle the division (show/hide) accordingly.
division.style.display = isShown ? 'block' : 'none';
// Due to the fact that the event listener is attached to the parent of the checkBox, we need to maintain consistency manually.
checkBox.checked = isShown;
}
// Remove from the array of DOMElements those that aren't checkboxes and add a click event listener to each of them.
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el) {
el.addEventListener('click', clickCallback, false);
});
// Call the function passing the dom elements with class '.seq-box-form-field' as argument. Checkboxes are contained within them. Also, transform the nodelist
// into a proper array so that methods defined in Array.prototype can be used.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')));
The code is commented and (I think) quite self-explanatory. However, if you have any doubt or want me to elaborate any point further, please, let me know.
Finally, here's the working fiddle.
UPDATE
Same function (more or less) but now it accepts an array of values that will correspond to the initial state of the checkboxes:
(function (domElements, cbState) {
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
}
domElements
.filter(function (el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function (el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
// Initial state of the checkboxes goes in the second parameter. The index in the array correspond to the checkbox position in the page.
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
Here's the Fiddle to play with. Hope it helps.
The other half of your problem, not addressed in the other answer has to do with events. Generally, adding an "onclick" attribute to the actual HTML is considered bad practice. You can attach event handlers with Javascript.
var a = document.getElementById("checkboxopt1");
a.addEventListener("click", exFunction, false);
See the manual for more info about how to use this.
Looks like that you need the elements that have the class "field-summernote", but not the class "editorbdyvar".
You can use a query selector to get elements by class name using the default tools from Javascript:
var items = document.querySelectorAll('.field-summernote');
for(var i = 0; i<items.length; i++){
var current = items[i];
if( current.className.indexOf('editoraccvar') < 0) //not found: -1
return;
//now you can manipulate the current element
console.log(current);
}
well ... you should either learn javascript, DOM, HTML and CSS or hire an somebody that can do it.
in my opinion the latter would come cheaper.
if not,
here goes something to put in your script.js file.
the checkboxes must have the id="toggleTextareas" respectively id="toggleInputs".
(function isolateScope() {
tryInit();
function tryInit() {
if(document.readyState!="complete"){
setTimeout(tryInit, 100);
}else{
createUI();
init();
}
}
function createUI(){
var div=document.createElement("div");
div.className="addon-floating-toolbar"
div.style.position="fixed";
div.style.zIndex="999999";
div.style.background="#EEE";
div.style.padding="5px";
div.innerHTML='<input type="checkbox" id="toggleTextareas">toggle Textareas<br>'
+'<input type="checkbox" id="toggleInputs">toggle Inputs';
document.body.appendChild(div);
}
function init() {
var tta=document.getElementById("toggleTextareas");
var ti=document.getElementById("toggleInputs");
var textareaVisible=true;
var inputVisible=true;
tta.onclick=toggleTextareas;
ti.onclick=toggleInputs;
function toggleTextareas() {
var elms=document.querySelectorAll("textarea");
textareaVisible=!textareaVisible;
if (textareaVisible) {
show(elms);
}else{
hide(elms);
}
}
function toggleInputs() {
var elms=document.querySelectorAll("input");
inputVisible=!inputVisible;
if (inputVisible) {
show(elms);
}else{
hide(elms);
}
}
function show(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="";
}
}
function hide(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].style.display="none";
}
}
}
})();
let me know if it works,
cheers.
You can traverse all your fields and generate a checkbox that will toggle it open/close for each of your fields. Also set the checkbox label as innerText of the corresponding field.
// Block to be run
generateCheckboxes = function() {
var button = document.getElementById("generateButton");
button.parentNode.removeChild(button);
// grab all elements with the class, .field-summernote
var uiblocks = [].slice.call(document.querySelectorAll('.field-summernote')).filter(function(x) {
return x.className.indexOf('editoraccvar') >= 0
});
if (!uiblocks.length) return;
var chcontainer = document.createElement('div');
chcontainer.style.display = "inline-block";
document.body.insertBefore(chcontainer, document.body.children[0]);
uiblocks.forEach(function(x) {
var cdiv = document.createElement('div');
var clabel = document.createElement('label');
clabel.innerHTML = x.innerText.trim();
var cinput = document.createElement('input');
cinput.type = 'checkbox';
cinput.checked = true;
cinput.onchange = function(ev) {
var checked = this.checked;
x.style.display = checked ? "" : "none";
}
cdiv.appendChild(clabel);
cdiv.appendChild(cinput);
cdiv.appendChild(document.createElement('br'));
chcontainer.appendChild(cdiv);
})
};
#container {
width: 150px;
}
input {
float: left;
}
label {
width: 120px;
display: block;
float: right;
text-align: left;
}
<button onclick="generateCheckboxes()" id="generateButton">Generate Checkboxes</button>
<div id="example" class="field-summernote editoraccvar">
<br/>
<br/>
<span>Zero</span>
<br/>
<textarea></textarea>
</div>
<div id="example1" class="field-summernote editoraccvar1">
<br/>
<br/>
<span>One</span>
<br/>
<textarea></textarea>
</div>
<div id="example2" class="field-summernote">
<br/>
<br/>
<span>Two</span>
<br/>
<textarea></textarea>
</div>
Fiddle
I am new at Javascript and jQuery. I need help with something like:
<script type="text/javascript">
$(window).load(function(){
$('#createDiv').click(function (){
$("<div/>").html("<span id='myInstance2' style='display: block;'>New Folder</span>").css("display", "none").appendTo("#results").fadeIn();
});
});
</script>
I have this function to click and create a new <span> tag with a text. You can see I have an ID myInstance2. So what I am trying to do is when I click and the span is created, I would like to make this span live-editable. Like I can rename this "New folder" into whatever I want.
If anyone can help it would be great. Thanks in advance and sorry for my bad English :)
If I catch what I think you're trying to do, it's not quite feasable the way you imagine. However, there are tricks. The following is one of them. The idea is to insert a "hidden" input where the span is, then create functions to show the input and hide span when needed (like when user clicks on span. Something like so:
jsFiddle
HTML
<button id="createDiv">Start</button>
<div id="results"></div>
CSS
#createDiv, #results span { cursor: pointer; }
#results div {
background: #FFA;
border: 1px solid;
margin: 1em;
padding: 1em 1em 2em;
}
#results input[type=text] {
border: none;
display: none;
outline: none;
}
JavaScript
// Call for document .onload event
$(function() {
// Normal Click event asignement, same as $("#createDiv").click(function
$("#createDiv").on("click", function(e) {
// Simply creating the elements one by one to remove confusion
var newDiv = $("<div />", { class: "new-folder" }), // Notice, each child variable is appended to parent
newInp = $("<input />", { type: "text", value: "New Folder", class: "title-inp" }).appendTo(newDiv),
newSpan = $("<span />", { id: "myInstance2", text: "New Folder", class: "title-span" }).appendTo(newDiv);
// Everything created and seated, let's append this new div to it's parent
$("#results").append(newDiv);
});
// the following use the ".delegate" side of .on
// This means that ALL future created elements with the same classname,
// inside the same parent will have this same event function added
$("#results").on("click", ".new-folder .title-span", function(e) {
// This hides our span as it was clicked on and shows our trick input,
// also places focus on input
$(this).hide().prev().show().focus();
});
$("#results").on("blur", ".new-folder .title-inp", function(e) {
// tells the browser, when user clicks away from input, hide input and show span
// also replaces text in span with new text in input
$(this).hide().next().text($(this).val()).show();
});
// The following sures we get the same functionality from blur on Enter key being pressed
$("#results").on("keyup", ".new-folder .title-inp", function(e) {
// Here we grab the key code for the "Enter" key
var eKey = e.which || e.keyCode;
if (eKey == 13) { // if enter key was pressed then hide input, show span, replace text
$(this).hide().next().text($(this).val()).show();
}
});
})
what you can do is put a delegated event handler on the enclosing, static element where span will reside #results. The handler will hide the span and reveal an input. I don't know your code well enough but you likely want the id on the input instead of the span. You did not say you wanted to go from editable back to "read-only" so I did not do that.
DEMO
$('#createDiv').on('click', function () {
var str = "Click here to edit it"; // New Folder
$("<div/>").html("<span id='myInstance2' class='editToggler' style='display: block;'>" + str + "</span><input class='editToggler' style='display: none' value='" + str + "'/>").appendTo("#results").fadeIn();
$(this).off('click');
});
$('#results').on('click', 'span', function () {
$('.editToggler').toggle();
});
This should work and is much simpler than other answers (imo):
<script type="text/javascript">
$(window).load(function(){
$('#createDiv').click(function (){
$("<div />").html("<span onclick='$(this).html(prompt(\"Rename \"+$(this).html()))' id='myInstance2' style='display: block; cursor:pointer;'>New Folder</span>").css("display", "none").appendTo("#results").fadeIn();
});
});
</script>
When you click your span, you will be prompted for its new name. To visual represent that your created the span is clickable, I also added cursor:pointer to the style for the span.
Demo: http://jsfiddle.net/XJ6Cn/
Edit: P.S: Do you create more than one spanusing this method? If so, you should create the ids dynamically, because ids are meant to be unique. If you want a string to be the same for all spans, you can set it as a class instead.
i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}
I'm a little confused why doesn't this code work!
The HTML Markup:
<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda"></div>
The JavaScript code:
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
alert (range.text);
}
}
}
var butn = document.getElementById("soda");
butn.onclick = function(){
GetSelectedText();
}
One problem that you may well be experiencing is that in some browsers (notably IE), by the time the button's click event fires, the selection has been destroyed. You can fix this by using the mousedown event instead (which still allows the selection to be destroyed, but only after the event has been handled), or by making the button unselectable.
I assume your button is not an actual button input, because this behaviour only happens for regular elements.
Demo: http://jsfiddle.net/L9bvU/1/
function GetSelectedText () {
if (window.getSelection) { // all browsers, except IE before version 9
var range = window.getSelection ();
alert (range.toString ());
}
else {
if (document.selection.createRange) { // Internet Explorer
var range = document.selection.createRange ();
alert (range.text);
}
}
}
span {
background-color: #ccc;
padding: 3px;
border: solid gray 1px;
}
*[unselectable="on"] {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
<div contenteditable="true">Please select some of this text and press a button below</div>
<span onclick="GetSelectedText()">Click</span>
<span onmousedown="GetSelectedText()">Mousedown</span>
<span unselectable="on" onclick="GetSelectedText()">Click, unselectable</span>
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
if (window.document.getSelection) {
return window.document.getSelection();
}
if (window.document.selection) {
return window.document.selection.createRange().text;
}
return "";
}
<p onmouseup="getSelectedText(); alert(txt)">
Highlight some of this text
with the mouse select press button end release
to fire the event. </p>
This is my way. You just need to select the text end alert text or anything else.
Does anyone know how OnMouse(event) set for the entire document in html, and it does not have to be directly added to html page.
To be on the other side, as we can change the elements in firebug!>-examples
Well there are two problems with the above code.
-You can't be guaranteed that
var butn = document.getElementById("soda");
will work because it may execute before the document is done loading
-When you click on another element that's not a button, the selection is lost. If you change the "soda" div to then it will work:
<div id="diva"><b>Score</b> some <i>goals</i></div>
<div id="soda" onclick="GetSelectedText()">This will NOT work</div>
<input type="button" onclick="GetSelectedText()" value="This will work"/>
However I strongly recommend you look at jQuery as the others here have advised; it will make your like a lot easier!
I'm trying to use Zeroclipboard http://code.google.com/p/zeroclipboard/ to copy stuff to the clipboard and add a tooltip when the mouse hover on the flash. but it doesn't seem to be working.
my html code:
<div rel="<?php echo $url;?>" class="cp-code">copied code</div>
<div class="test" style="display: none; border: 1px solid #ccc; padding: 8px;">click copy,test,test</div>
My js code: i have added the jquery library.
ZeroClipboard.setMoviePath("http://example.com/js/ZeroClipboard.swf");
var clip = null;
var url = '';
function init() {
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
$('.cp-code').mouseover( function() {
clip.setText(this.innerHTML);
$('test').style.display = 'block';
if (clip.div) {
clip.receiveEvent('mouseout', null);
clip.reposition(this);
} else {
clip.glue(this);
}
clip.receiveEvent('mouseover', null);
url = $(this).attr('rel');
});
clip.addEventListener('mouseUp', function(client) {
window.open(url);
});
clip.addEventListener('mouseOut', function (client) {
$('test').style.display = 'none';
});
}
$(document).ready(function() {
init();
});
Why do you want it to happen on mouseover? I'm not sure if ZeroClipboard supports that.
It took me a little while to figure this out when I first used ZeroClipboard because it's implementation is a bit different from normal. However, you can't just call clip.setText. You have to 'glue' the clip implementation to the control. And you can't use the jQuery object either, you have to glue it to the actual DOM object.
So, for example:
var cpCode = $('.cp-code');
cpCode.each(function()
{
clip = new ZeroClipboard.Client(); //you can set the movie path here too
clip.glue($(this)[0]); // The [0] accesses the actual DOM object rather than the jQuery object
clip.setText($(this).html();
});
So now when you click the element, the text will be copied.I see where your doing some other stuff in your example, but regardless, I think the element your missing is gluing the DOM object to the instance of clip, rather than calling clip.setText on your jQuery mouseover event.