Run same javascript independent from each other - javascript

Working on the following demo, I have got a problem about making the code work twice (or more times).
I just wanted to add more "before/after" images, but seems like the draggable bar only works on the main one, and applies the movement to the others.
Is there any solution to make it work independent from each one?
Where could be the error:
$(function(){
var $dragMe = $("#dragme");
var $beforeAfter = $("#before-after");
var $viewAfter = $(".view-after");
Draggable.create($dragMe, {
type:"left",
bounds: $beforeAfter,
onDrag:updateImages
});
DEMO: JSFIDDLE

As answered on my previous post by #Jonas Grumman, here goes the solution:
JSFIDDLE
The main problem was on executing two ID tags on the same html page.
Otherwhise was my mistake since I forgot to change it on css, so focusing only on html & javascript was an error.
So modifying the following parts, was enough:
HTML (before):
<div id="dragme"></div>
HTML (after):
<div class="dragme"></div>
Javascript (before):
var $dragMe = $("#dragme");
Javascript (after):
var $dragMe = $(".dragme");
CSS (before):
#dragme{
some css styles here
}
CSS (after):
.dragme{
some css styles here
}

Related

Display:flex does not load correctly on anchor tag?

I'm working on a full-stack project that is somehow loading inconsistent CSS styles on my anchor elements. Using Javascript I am doing something like the following:
recordData.forEach(record => {
let a = help.createElement('a');
let text = record.jobTitle + " (" + record.deptName + ", " + record.subDeptName + ")-" + record.email;
a.textContent = text;
a.href = `/frontend/contractorForm/contractorForm.html`;
a.addEventListener('click', function(event) {
sessionStorage.clear();
sessionStorage.setItem('record', JSON.stringify(record));
}, false);
parent.appendChild(a);
}
The idea of this was that although I have one single HTML form "template" created, I can populate the values inside contractorForm.html through values stored in my sessionStorage.
Below are my anchor tag frontend views and I also attached images of what happens when I click on other ones. The problem with this is that when I click on my anchor tags on the front end, this is what I get.
My CSS for contractorForm.html is basically display:flex; justify-content:center. But as shown in the images, only the first anchor link works.
Things I've checked and verified: CSS page does load when looking at Devtools, disabling and clearing cache, attaching ?version={random number} onto the .html href, changing style on devtools to see if it works (and it does), changing the background color (it works perfectly), loading my CSS code after bootstrap link, checking paths and links (all correct)
The only issue here is that my display: flex is simple just not working. Any help or ideas will be appreciated! Thank you!
anchortaghtmlview
first-anchortag-click-view
second-anchortag-click-view
Fixed it - if you have CSS issues, make sure you are referring correctly to the parent.
My CSS looked like this before:
#contractor-form-section {
width: 50rem;
}
#contractor-form is wrapping just the form element, and the way how my DOM structure looked like was something like this:
<body>
<div id="contractor-form-border">
<section id="contractor-form-section">
<h1>...</h1>
<form>
</form>
</section>
</div>
</body>
Essentially, my CSS was referring to #contractor-form-section rather than #contractor-form-border. Switching to that basically fixed the issue!

Display table cell content in tooltip (jsfiddle won't work on real site)

I am trying to have the full table cell content show as a tooltip. This will let visitors see the part that is hidden since it is too long to fit in the cell.
I am attempting the solution described here (please look there to see expected behavior):
http://jsfiddle.net/zWfac/
var container = $("#container");
$("td").hover(function ()
{
container.children(".tooltip").remove();
var element = $(this);
var offset = element.offset();
var toolTip = $("<div class='tooltip'></div>");
toolTip.css(
{
top : offset.top,
left : offset.left
});
toolTip.text(element.text());
container.append(toolTip);
});
I changed the container var definition from an id to a class:
var container = $(".sortTable");
I added the code to our wordpress site by putting it right before </body> in my child theme's footer.php, inside a jQuery().ready(function() block.
I am getting an error that leads me to think jQuery is not properly initializing but I am too new to this language to be able to troubleshoot effectively. I'd appreciate any suggestions on this.
I have a sample table on this page:
http://frugalmule.com/overflow/
Please note my client previously posted a somewhat incomplete question about this which was removed; I have made many changes to the page since then but I still don't have what he needs. Since the error occurs when putting the JSFiddle to the real site, I don't know how to state the problem in any simpler fashion.
Please replace $ with jQuery in your script. This will solve your problem. You can refer this link: http://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/

remove html tag using jquery/javascript

I have an html element on my website that is being put there beyond my control and I need to remove it using javascript/jquery. The HTML tag is consistent and on every page, it looks like this:
<img src="https://myimage.com/myimage.jpg" style="cursor:pointer;border:none;">
how do I remove it? The image has no ID. Thanks so much in advance!
You can remove it like this:
jQuery("img[src='https://myimage.com/myimage.jpg']").remove();
Be sure that that code is in a script tag below the relevant image in the markup of the page. If the image is being added dynamically after the page markup has been parsed, you may have to be more crafty:
(function() {
function removeImage() {
var img = jQuery("img[src='https://myimage.com/myimage.jpg']");
if (img.length) {
// It's there now, remove it
img.remove();
}
else {
// Not there yet, check again in a quarter of a second
setTimeout(removeImage, 250);
}
}
removeImage(); // Start the process
})();
Note: You're removing an element, not a tag. Tags are markup (text). Elements are the result of tags being parsed and created by the browser.
use
$("img[src='https://myimage.com/myimage.jpg']").remove();
That will hide that image
Here you go
$("img[src='https://www.google.com/images/srpr/logo11w.png']").remove();
http://jsfiddle.net/bowenac/GD64n/
Mind explaining what the image is or post a live link? This will remove it from displaying but will not fix the source of the problem if this is some kind of hack placing this code into your files...
No jQuery, plain JS:
var img = document.querySelector('img[src="https://myimage.com/myimage.jpg"]');
if (img) {
img.parentNode.removeChild(img);
}

HTML document pagination without jQuery

I have a large page having a lot of divs and all these divs are enclosed in a single div. And I have number links on the top of the page equal to the total enclosed divs I have. Now what I want to do is, on click on a number, I want to show only div corresponding to that number and hide all other.
links--> 1 2 3 4 5 6 7 .....
<div id="all">
<div id="mail1">..........</div>
<div id="mail2">..........</div>
<div id="mail3">..........</div>
<div id="mail4">..........</div>
<div id="mail5">..........</div>
<div id="mail6">..........</div>
.....and so on
</div>
I have to do it inside an HTML and that HTML will be stored and may be viewed offline as well, so cannot use jQuery here. Have to do it using JavaScript itself.
Could anybody help me with the JavaScript code here?.
<script type="text/javascript">
var divIds = ["mail1", "mail2", ..., "mailn"];
function showDiv(showId) {
for(var i = divIds.length; i--; ) {
if(divIds[i] === showId)
document.getElementById(showId).style.display = "block";
else
document.getElementById(divIds[i]).style.display = "none";
}
}
</script>
Then your links at the top will look like this:
1
Haven't tested it, but that's the idea. Downsides are you have to maintain the div in 3 places in code
In the var divIds array.
In the html tag itself.
In the links across the top.
You could write some javascript to generate all 3, taking away the maitenance part of it entirely.
As for using jQuery in an offline doc, the best route would probably be to include the text of the jquery.min.js file in the doc itself inside of <script></script> tags. That way you don't have to worry about paths and what-not.
You may do something like that (don't judge me on js coding style, i'm not a js ninja):
window.onload = function() {
var outer = document.getElementById("all");
for (var i=0; i < outer.childNodes.length; i++) {
outer.childNodes[i].addEventListener("click", doSomething);
}
function doSomething() {
// here you can run loop for changing display style for you divs
console.log(this.id);
}
}
I made an unobtrusive example without knowing the div ids:
http://jsfiddle.net/8pQzx/2/
Its more code but this is what you get if you dont want to use a js lib. ;)

Wrapping a jquery validate span.error with nested divs

Heyo. This is my first stack overflow post because I am stumped and not finding many people who are trying to accomplish the same thing. I've tried using jquery .before(), .after(), and .wrap() to resolve this. I was initially using css :before and :after pseudo-elements, but as that won't work for legacy browsers, I've decided to use jquery.
I already have several forms on several pages with validation working. The error messages vary in length. We were using a static, one size background image on the default span element, so content was bleeding out on longer error messages. I built a flexible rounded corner series of nested divs to allow the error box to grow or shrink dynamically. The html I want to output is:
<div class="errorWrap">
<div class="errorTop"><span></span></div>
<div class="errorContent">
<span class="error">This is an error</span>
</div>
<div class="errorBottom"><span></span></div>
</div>
Here's an example of a solution I tried, but I'm still pretty new to javascript.
$('.error').before('<div class="errorWrap"><div class="errorTop"><span></span></div><div class="errorContent">');
$('.error').after('</div><div class="errorBottom"><span></span></div></div>');
Correct me if I'm wrong, but I think that I have the right idea with the jquery. But it's just kind of sitting there, not in any function being called. So I imagine that since the code isn't re-executing, it just doesn't show up. Is there an appropriate function to wrap this in? I'm certain I'm just not attacking this from the right direction. Any help is super appreciated.
the plugins "before" and "after" dont take html as string. you cannot start a div in one and close it in an other.
Either you take your current html and generate a new html string which you append where you want to or you use the "wrap" plugin http://api.jquery.com/wrap/
Using pure HTML
$(".error").html("<div class='beforeContent'>" + $(".error").html() + "</div>");
Using wrap (http://api.jquery.com/wrap/)
$(".error").wrap("<div class='beforeAndAfter'></div>");
If you want to show an error div after focus out of an input then you have to create it using html/wrap as Luke said and then you have to append it in ot the dom useing
$('.errorWrap').insertAfter('.focusedElement');
But there are other methods available to insert a new element like append/appendTo e.t.c,
I ended up fixing this problem on my own using jquery to create the div and it's nesting on pageload, the divs are generated with an error class that gives display:none. A custom errorPlacement function nests the error in the correct div. Then I used a custom validator highlight function to remove the class that hides the element. Then I used the unhighlight function to re-add the class to re-hide the div.
$(function() {
//Generate the elements and assign attributes
var errorWrap = document.createElement('div');
$(errorWrap).addClass('errorWrap hideError');
var errorTop = document.createElement('div');
$(errorTop).addClass('errorTop');
var topSpan = document.createElement('span');
var errorContent = document.createElement('div');
$(errorContent).addClass('errorContent');
var errorBottom = document.createElement('div');
$(errorBottom).addClass('errorBottom');
var bottomSpan = document.createElement('span');
//Place the elements directly after each dd element
$("dl > dd").append(errorWrap);
$("div.errorWrap").append(errorTop)
.append(errorContent)
.append(errorBottom);
$("div.errorTop").append(topSpan);
$("div.errorBottom").append(bottomSpan);
//Add custom validator defaults
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).nextAll('.errorWrap').children('.errorContent').append(error);
},
highlight: function(element) {
$(element).nextAll('.errorWrap').removeClass('hideError');
},
unhighlight: function(element) {
$(element).nextAll('.errorWrap').addClass('hideError');
}
});
}
Although I'm sure this could have been done more shorthand, I really like this technique because I didn't have to update any of my pages that contained forms to get it to work. All of the nested divs are dynamically created by javascript, so I can include a global file to any page with forms and it will just work. Thanks for all who offered suggestions.

Categories

Resources