Insert a div and remove it within js function - javascript

I have a script here that requires a bit of manual work done. The developer doesn't provides modification support and I am not exactly JS proficient so I need some help. Basically the script below shows a woocommerce product image, and there's a preload function. I need to insert a div called .temp-image before the preload_img.onload = function and remove the div within preload_img.onload
if ($(img).length > 0) {
img.data('tm-current-image', false);
var a = img.closest("a");
var a_href_original = a.attr('href');
main_product.on('tm_change_product_image', function(e) {
var tm_current_image_element_id = e.element.attr('name'),
$main_product = e.main_product;
var clone_image = img.tm_clone(),
preload_img = new Image();
preload_img.onload = function() {
$main_product.find('#' + tm_current_image_element_id + '_tmimage').remove();
$main_product.find('.tm-clone-product-image').hide();
clone_image.prop('src', preload_img.src).hide();
img.hide().after(clone_image);
clone_image.show();
if (is_iosSlider) {
setTimeout(function() {
is_iosSlider_element.iosSlider('update');
}, 150);
}
};
clone_image
.attr('id', tm_current_image_element_id + '_tmimage')
.addClass('tm-clone-product-image').hide(); //.show();
preload_img.src = e.src;
a.attr('href', e.src);
img.data('tm-current-image', tm_current_image_element_id);
if (is_yith_wcmg) {
yith_wcmg.yith_magnifier('destroy');
yith_wcmg.yith_magnifier(yith_magnifier_options);
}
});
}

i am not clear your question but you can add div using this, suppose you want add div after this is div and you want to add div after this
<script type="text/javascript">
$(".test").append("<div id='specificdiv'>hello world</div>");
</script>
or
<script type="text/javascript">
$("<div id='specificdiv'>hello this is added div</div>").appendTo(".test");
</script>
or
<script type="text/javascript">
$("<div></div>").attr('id','specificdiv').appendTo('body');
</script>
and remove it
<script type="text/javascript">
$( "#specificdiv" ).remove();
</script>
or
<script type="text/javascript">
$( "#specificdiv" ).empty();
</script>

Related

ReferenceError: jQuery is not defined in self invoking function

I've tried all the solutions from other Stackoverflow topics, but I can't my jQuery file to work.
I use a Wampserver to test my code and I test inside of multiple browsers (Firefox, Chrome, Opera). Same problem every time.
HTML
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
I've put these lines before my closing <\body> tag
scripts.js`
(function($) {
'use strict';
// holds current image shown
var $currNr = 0;
var links, images;
/**
* Function to prevent closures; adds click event handler to links
*/
var addEvents = function(nr) {
// add click event to link
$(links[nr]).on('click', function(e) {
showImage(nr);
e.preventDefault();
});
};
/**
* Function to show an image
*/
var showImage = function(nr) {
// find image
var $img = $(images[nr]);
if (!$img) return;
// find big image
var $photoBig = $('#photoBig');
// change
$photoBig.attr('src', $img.attr('data-src-l'));
$photoBig.attr('alt', $img.attr('alt'));
// remember current image number
$currNr = nr;
};
/**
* Function to show the next image
*/
var showNextImage = function() {
if ($currNr != (links.length - 1)) {
showImage($currNr + 1);
} else {
showImage(0);
}
};
/**
* Function to show the previous image
*/
var showPrevImage = function() {
if ($currNr != 0) {
showImage($currNr - 1);
} else {
showImage(links.length - 1);
}
};
// start scripts
$(window).on('load', function() {
// find images and links
links = $('#thumbsmenu li>a');
images = $('#thumbsmenu li>a img');
// add link events
$(links).each(function(nr) {
$(this).on('click', function(e) {
showImage(nr);
e.preventBubble();
});
});
// controls
$('#lnkFirst').on('click', function(e) {
showImage(0);
e.preventDefault();
});
$('#lnkPrev').on('click', function(e) {
showPrevImage();
e.preventDefault();
});
$('#lnkNext').on('click', function(e) {
showNextImage();
e.preventDefault();
});
$('#lnkLast').on('click', function(e) {
showImage(images.length - 1);
e.preventDefault();
});
// keyboard
$(document).on('keydown', function(e) {
var $code = (e.keyCode ? e.keyCode : e.which);
switch (event.keyCode) {
case 37: showPrevImage(); e.preventDefault(); break;
case 39: showNextImage(); e.preventDefault(); break;
}
});
// play
var $timer;
$('#btnPlay').on('click', function(e) {
if (!$(this).prop('playing')) {
$(this).val('stop');
$(this).prop('playing', true);
$currNr = 0;
$timer = setInterval(showNextImage, 1000);
} else {
$(this).val('start');
$(this).prop('playing', false);
clearInterval($timer);
}
});
});})(jQuery);`
I use a self-invoking function and use it as parameter but I get a:
ReferenceError: jQuery is not defined
Normally this code should work, that was how I was taught back then. Anyone an idea what could be the real issue here?
You are loading scripts.js before jQuery
Change the following code:
<script src="js/scripts.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
To:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>
Your script load ordering is wrong. Load jQuery first, then use it.
As other people suggested your order is wrong. In order for you to use JQuery in other script files it needs to be fully loaded. Change your HTML like so:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/scripts.js"></script>

How do I add this code to what I already have in oder for this code to work

I would like to implement the second code into the first one in order for it to work as intended. I am unsure how to do this
Current code:
<script type="text/javascript">
!function(){
var campaign_link = ""; // REPLACE WITH YOUR LINK
var t;
try{
for(t=0;10>t;++t)history.pushState({},"","#");
onpopstate=function(t){t.state&&location.replace(campaign_link + window.location.search.substring(1))}}
catch(o){}
}();
</script>
the code I would like to add to existing code;
window.addEventListener("popstate", function(e) {
window.location.href = location.href;
});
You can just add this function to your current script like so. However you may want to store the loction.href in a var as opposed to window.location
<script type="text/javascript">
function(){
var campaign_link = ""; // REPLACE WITH YOUR LINK
var t;
try{
for(t=0;10>t;++t)history.pushState({},"","#");
onpopstate=function(t){t.state&&location.replace(campaign_link + window.location.search.substring(1))}}
catch(o){}
}();
window.addEventListener("popstate", function(e) {
window.location.href = location.href;
});
</script>

pagination by using jquery

I would like to make pagination in jQuery, but it is not working. JavaScript is working, but jQuery code is not working. I think that the variable num is the problem.
What is the problem in this code?
jQuery
<script type="text/javascript">
jQuery(document).ready(
function fn_page(num) {
document.form1.target = "_self";
document.form1.action = "";
document.form1.page.value = num;
//document.form1.submit();
/* jQuery("form1").attr('target', '_self').submit(); */
}
);
</script>
JavaScript
<li>{$p_num}</li>
You don't need to wrap this function in (document).ready.
Change it to this (assuming the id of your form is id="form1":
<script type="text/javascript">
function fn_page(num) {
document.forms['form1'].target = "_self";
document.forms['form1'].action = "";
document.forms['form1'].page.value = num;
document.forms['form1'].submit();
}
</script>
And really, since you're using jQuery, you should just stay true to your abstraction:
<script type="text/javascript">
function fn_page(num) {
jQuery("#form1").attr("target", "_self");
jQuery("#form1").attr("action", "");
jQuery("#form1 input[name=page]").val(num);
jQuery("#form1").submit();
}
</script>

Implemeting Create and Delete function properly using javascript

I am able to create a div using javascript. However, not able to remove that div that I created previously. Only after post-back, I can remove that div. Actually after creating div, script cannot find that div because page did not loaded again.
What I want to do is to create a page that I am able to add an item and remove that item.
Add script works fine.
Remover script:
<script type="text/javascript">
$(function () {
$('.remove ,.shop-button-large, .shop-button-add').click(function () {
var itemToDelete = $(this).attr("data-id");
if (itemToDelete != '') {
$.post("/ShoppingBox/RemoveFromBox", { "id": itemToDelete },
function (data) {
$("#boxItem-" + itemToDelete + "-" + data.ItemCount).fadeOut(300);
});
}
});
});
</script>
The click handler for the remove was done before the DOM node was rendered. It needs to be insider the $(function() { ... }
http://plnkr.co/edit/IhtyH6ampodXICPBv6Fq?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(function() {
$("#create").click(function() {
var createDiv = document.createElement("div");
createDiv.id = "myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
$("#remove").click(function() {
console.log('remove', $("#myDiv"));
$("#myDiv").fadeOut(300);
});
});
</script>
</head>
<body id="myBody">
Create
Remove
</body>
</html>
In order to clarify, I have prepared a simple code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery-2.1.3.intellisense.js"></script>
<script src="js/jquery-2.1.3.min.js"></script>
<script src="js/jquery-2.1.3.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function () {
$("#create").click(function () {
var createDiv = document.createElement("div");
createDiv.id ="myDiv";
createDiv.style.margin = "0 auto";
createDiv.style.width = "600px";
createDiv.style.height = "600px";
createDiv.style.backgroundColor = "red";
document.getElementById("myBody").appendChild(createDiv);
});
});
$("#remove").click(function () {
$("#myDiv").fadeOut(300);
});
</script>
<title></title>
</head>
<body id="myBody">
Create
Remove
</body>
</html>

redirecting to other page with value in javascript via click

I want to create a Javascript file to do these operations:
Pass the current link to the other page
Click on hypertext or image that is created dynamically in JavaScript file to redirect
Just I want to have a Javascript link in the html body and not other thing same this :
<div>
<script type="text/javascript" src="JScript.js"></script>
</div>
And in the JavaScript file I have these:
var DivTag = document.createElement("Div");
DivTag.setAttribute('ID', 'MyDivTagID');
$(document).ready(function () {
$("$MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + window.location;
});
});
This is not working. Please help me.
Several issues
you never added the div to the page
you used $ instead of # to access the div by ID
you do not consistently use jQuery
Plain JS: DEMO HERE
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
DivTag.innerHTML="Click";
DivTag.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
document.body.appendChild(DivTag);
}
Using linked image:
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
var anchor = document.createElement("a");
anchor.href="#";
anchor.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
var img = document.createElement("img");
img.src="image.gif";
img.style.border="0";
anchor.appendChild(img);
DivTag.appendChild(anchor);
document.body.appendChild(DivTag);
}
jQuery: DEMO HERE
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>');
$("#MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
A small change to the jQuery code from mplungjan:
Change:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
To:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').find('#MyDivTagID').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
If you output e.currentTarget from the anonymous click handler function you get body since the event handler was attached to the body in mplungjan's solution. All I did was add .find('#MyDivTagID') directly after the .append() function so the click handler gets attached to the div and not the body.

Categories

Resources