why wont jQuery remove() work in this case? - javascript

Im trying to cause a canvas element to be added to the DOM and then removed after a set time. The killbox() function gets called, but the element is not removed. I believe I have the syntax right, and that there is some underlying issue with removing dynamically added DOM elements.
//con is short for console.log()
function spawnCanvas(e) {
con(e);
var boxheight=50;
var boxwidth=50;
var xpos = e.clientX - boxwidth/2;
var ypos = e.clientY - boxheight/2;
var id = xpos.toString() + ypos.toString();
con("id:" + id);
var tag = "<canvas width='" + boxwidth +
"' height='" + boxheight +
"' style='position:absolute; border:1px solid #000; left:" +
xpos + "px; top:" + ypos + "px;' id='" + id + "'></canvas>";
con(tag);
var t = $(tag);
$("body").append(t);
var p = setTimeout("killbox(" + id + ")", 1500);
}
function killbox(id){
con("in killbox. id:" + id);
$('#id').remove();
}

Within killbox you are removing the element with the literal id id. Instead try;
$('#' + id).remove();
The above will remove the element that has the id that the "id" variable is set to.

Are you sure you don't want $("#" + id).remove();?

because you are searching with an element with the ID id, but you rather wanted to pass the parameter from the function
function killbox(id){
con("in killbox. id:" + id);
$('#'+id).remove();
}

Related

I'm trying to change the syntax in this code

I'm a beginner in Javascript. I just wonder how I can use style instead of using a new var in this code.
var style =
"position:absolute;" +
"width:" + newObj.radius + "px;" +
"left:" + newObj.xPos + "px;" +
"top:" + newObj.yPos + "px;";
newImg.setAttribute("style", style);
I want the plus signs to be removed from the end of each line. I tried the following code, but it doesn't work.
newImg.style.position = "absolute;";
newImg.style.width= newObj.radius + "px;";
newImg.style.left = newObj.xPos + "px;";
newImg.style.top = newObj.yPos + "px;";
You question is how to set HTML element's CSS attributes using _Object_.style's properties vs. setting a style using string value
Like this:
newImg.style.position = "absolute";
newImg.style.width= newObj.radius + "px";
newImg.style.left = newObj.xPos + "px";
newImg.style.top = newObj.yPos + "px";
All of these can be found in CSS Reference documentation - look for Javascript syntax for each property
Try this
document.getElementById("theIdYouMadeInHTML").style.property = new style;
As shown in here: https://www.w3schools.com/js/js_htmldom_css.asp

Responsive Smooth Scroll CSS3 Animation?

I've been trying to get a smooth scroll animation for a while now, but mainly in JS..
This hasn't been working out that well so I decided to try in CSS3.
Now I want to make this animation responsive by calling a JS function which adds the CSS rules for the animation responsive to the object the animation is for. Here is the JS code I've got so far. I'll also leave a Fiddle, but I'm new to that so things might not work right away.
function getTexts() {
var element = document.getElementsByClassName('toplink');
for (x = 0, len = element.length; x < len; x++){
var ID = element[x].textContent.toLowerCase();
var object = document.getElementById(ID);
console.log(object);
addCSSAnimator(ID);
}
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = document.getElementById(el);
var Class = DOM.getAttribute("class");
var Parent = DOM.parentElement.getAttribute("id");
var rect = DOM.getBoundingClientRect();
var rule = ".toplink[ id= '"+el+"' ]:target - #"+Parent+" div."+Class+" {\n" +
"-webkit-transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"transform: translateY( +"+rect.y.toPrecision(4)+'px'+" );\n" +
"}";
console.log("Stylesheet: ",sheet," object: ",DOM," Class: ",Class," offset X&Y:",rect.x," ",rect.y);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
https://jsfiddle.net/dtj46c64/
You may try moving to jquery for this solution. Use document.ready and window.resize functions to handle the animation and also instead of for loop. use the jquery .each() function to get the elements. Try working around the following code i changed for you to go along with. Hope this puts you in the right direction to achieve your goal:
<script>
function getTexts() {
$(".toplink").each(function () {
let ID = $(this)
console.log(ID);
addCSSAnimator(ID);
});
}
function addCSSAnimator(el) {
var sheet = document.styleSheets[0];
var DOM = el;
var Class = DOM.attr("class");
var Parent = DOM.parent().attr("id");
var rect = DOM[0].getBoundingClientRect();
var rule = ".toplink[ id= '" + el + "' ]:target - #" + Parent + " div." + Class + " {\n" +
"-webkit-transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"transform: translateY( +" + rect.top.toPrecision(4) + 'px' + " );\n" +
"}";
console.log("Stylesheet: ", sheet, " object: ", DOM, " Class: ", Class, " offset X&Y:", rect.left, " ", rect.top);
console.log(rule);
sheet.insertRule("body { background-color: 0; }", 1);
}
$(window).on('resize', function () {
getTexts();
});
$(document).ready(function () {
getTexts();
});
</script>
Notice i changed the rect.y to rect.top as on some browsers the getBoundingClientRect fucntion does not return x and y values but left and top are always filled.
Also dont know why you are getting id of the parent of the object as there is no id set to the parent of the anchor class="toplink" so it will always return as null or empty.
Sorry for not a 100% answer as got busy but i hope the solution so far i suggested will help you tweak and find what your looking for.

Textarea not generating from jQuery

I'm trying to make a website using jquery-1.11.1 where I want a <textarea> to be spawned whenever I click on the link which only shows on mouseenter on a div. But I'm getting an error in my console,
Uncaught ReferenceError: inputdivEditor is not defined (Please ignore JSFiddle errors)
I've absolutely no idea why I'm getting this. Here are my codes,
$(document).ready(function () {
$("[id^=divEditor-]").each(function () {
var content = $(this).html();
var targetID = $(this).attr('id');
var txtID = 'input' + targetID;
$('<textarea id="input' + targetID + '" name="' + txtID + '" >' + content + '</textarea>').insertBefore(this).css('display', 'none');
var button = "<a onclick='activateDivEditor(this, " + txtID + ")' class='custom-edit-button editDiv' id='active" + targetID + "'>Embed Code</a>";
$(this).on('mouseenter', function () {
$(this).prepend($(button));
$(this).css('position', 'relative');
});
$(this).on('mouseleave', function () {
$('.editDiv').remove();
});
});
});
function activateDivEditor(btn, txtId) {
var targetID = $(btn).parent().get(0).id;
var update = "<a onclick='deactivateDivEditor(this, " + txtId + ")' class='custom-edit-button updatediv' id='deactive" + targetID + "'>Update</a>";
var cancel = "<a onclick='cancelactivateDivEditor(this)' class='custom-edit-button cancel' id='cancelactive" + targetID + "'>Cancel</a>";
var targetClass = $('#' + targetID).attr('class');
var targetWidth = $('#' + targetID).width();
$('#' + targetID).css('display', 'none');
$('#input' + targetID).css('display', 'block').css('width', targetWidth - 2).css('height', '125px');
$('#input' + targetID).parent().css('position', 'relative');
$(update).prependTo($('#input' + targetID).parent());
$(cancel).prependTo($('#input' + targetID).parent());
}
JSFiddle Demo
How can I generate a textarea whenever I click on the button link? Need this help badly. Thanks.

jQuery attr() failing

In the following code, on the line commented "PROBLEM LINE", attr causes the console.log to print out "undefined" when you click on one of the s. I can't seem to figure out why:
test.js
var html = '';
// number of panels in the carousel
var panelCount = 0;
// panel that is to the forefront of the carousel
var currentPanel = 0;
$(document).ready(function(){
for (var i=0; i < 5; i++) {
html += '<div class="team-member" id="' + panelCount + '">' + panelCount + '</div>';
html += '<div class="reflection" id="' + panelCount + '"></div>';
panelCount++;
}
$('#carousel').html(html);
$(".container-carousel").on('click', '.team-member', function(e) {
var target = $(e.currentTarget);
var targetId = parseInt(target.attr('id'));
var frontRotation = currentPanel * (360/panelCount);
$("#" + targetId + ".reflection").css("transform", "rotateY( " + frontRotation + "deg ) translateZ( 288px ) translateY( 175px ) translateZ( 175px ) rotateX( 90deg )");
var targetIdString = '' + targetId;
/* PROBLEM LINE: */
$("#" + currentPanel + ".reflection").attr('id', targetId);
console.log($("#" + currentPanel + ".reflection").attr('id'));
$("#" + targetId + ".reflection").attr('id', currentPanel);
});
});
test.html
<!DOCTYPE html>
<!-- JQuery-->
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type = "text/javascript" src = "test.js"></script>
<section class="container-carousel">
<div id="carousel" style="transform: translateZ(-288px) rotateY(-360deg);"></div>
</section>
</html>
Any ideas why?
This is because immediately after you change the id of the element, you try logging by selecting with the old id.
$("#" + currentPanel + ".reflection").attr('id', targetId);
/*The id is now targetId*/
console.log($("#" + currentPanel + ".reflection").attr('id'));
/*currentPanel will not work because an element with that id no longer exists*/
Change your console.log to
console.log($("#" + targetId + ".reflection").attr('id'));
See it working here
The main problem in your code is, you have duplicate IDs in your page. So the id selector will always fetch the first element with the id, the tries to apply the .refelection class selector which does not match thus your selector $("#" + currentPanel + ".reflection") does not return any result.
So use 2 different ids for the team-member and reflection elements, I think you can use a suffix as shown below for 1 element
for (var i = 0; i < 5; i++) {
html += '<div class="team-member" id="' + panelCount + '">' + panelCount + '</div>';
html += '<div class="reflection" id="' + panelCount + '-reflection"></div>';
panelCount++;
}
then
$("#" + targetId + "-reflection").css("transform", "rotateY( " + frontRotation + "deg ) translateZ( 288px ) translateY( 175px ) translateZ( 175px ) rotateX( 90deg )");
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Jquery Scope Problems

function drawLabel(labelsIndex) {
// Check not deleted Label data:(DBID, text, styling, x, y, isDeleted)
if (!labelData[labelsIndex][5]) {
// Create
var newLabel = $('<div id="label' + labelsIndex + '" style="font-size:' + (labelData[labelsIndex][6] * currentScale) + 'px;z-index:9999;position:absolute;left:' + labelData[labelsIndex][3] + 'px;top:' + labelData[labelsIndex][4] + 'px;' + labelData[labelsIndex][2] + '">' + labelData[labelsIndex][1] + '</div>');
$('#thePage').append(newLabel);
// Click edit
$('#label' + labelsIndex).dblclick(function() {
if (!isDraggingMedia) {
var labelText = $('#label' + labelsIndex).html();
$('#label' + labelsIndex).html('<input type="text" id="labelTxtBox' + labelsIndex + '" value="' + labelText + '" />');
document.getElementById('#label' + labelsIndex).blur = (function(index) {
return function() {
var labelText = $('#labelTxtBox' + index).val();
$('#label' + index).html(labelText);
};
})(labelsIndex);
}
});
The code is meant to replace a div's text with a textbox, then when focus is lost, the textbox dissapears and the divs html becomes the textbox value.
Uncaught TypeError: Cannot set property 'blur' of null
$.draggable.start.isDraggingMediaresources.js:27
c.event.handlejquery1.4.4.js:63
I think I'm getting a tad confused with the scope, if anyone could give me some points I'd appreciate it. It would also be good if someone could show me how to remove the blur function after it has been executed (unbind?)
document.getElementById('#label' + labelsIndex).blur is a javascript function and less jquery :) therefore the # hash there is just irrelevant.
$('#label'+labelsIndex).bind('blur',function (){
//labelText value goes here //
});
EDIT
to be honest ur over complicating it :)
<div id="txt1">I am div</div>
<textarea id="txt2">I am text</textarea>
$('#edit_button').click(function (){
var val = $('#txt1').hide().html();// hide the div,then get value,
$('#txt2').show().val(val);//show txtarea then put value of div into it
});
Do the opposite for $('#save_button');

Categories